package de.tudarmstadt.informatik.hostage.ui2.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import de.tudarmstadt.informatik.hostage.Hostage;
import de.tudarmstadt.informatik.hostage.R;
import de.tudarmstadt.informatik.hostage.model.Profile;
import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
import de.tudarmstadt.informatik.hostage.ui.LogFilter;
import de.tudarmstadt.informatik.hostage.ui2.adapter.DrawerListAdapter;
import de.tudarmstadt.informatik.hostage.ui2.fragment.AboutFragment;
import de.tudarmstadt.informatik.hostage.ui2.fragment.HomeFragment;
import de.tudarmstadt.informatik.hostage.ui2.fragment.ProfileManagerFragment;
import de.tudarmstadt.informatik.hostage.ui2.fragment.RecordOverviewFragment;
import de.tudarmstadt.informatik.hostage.ui2.fragment.ServicesFragment;
import de.tudarmstadt.informatik.hostage.ui2.fragment.SettingsFragment;
import de.tudarmstadt.informatik.hostage.ui2.fragment.StatisticsFragment;
import de.tudarmstadt.informatik.hostage.ui2.fragment.ThreatMapFragment;
import de.tudarmstadt.informatik.hostage.ui2.fragment.UpNavigatibleFragment;
import de.tudarmstadt.informatik.hostage.ui2.fragment.opengl.ThreatIndicatorGLRenderer;
import de.tudarmstadt.informatik.hostage.ui2.model.DrawerListItem;

/**
 * @author Alexander Brakowski
 * @created 12.01.14 23:24
 */
public class MainActivity extends Activity {
	public static volatile Context context;

	/** singleton instance of the MainActivity **/
	private static MainActivity sInstance = null;

	public Fragment mDisplayedFragment;

	public Hostage mHoneyService;

	private DrawerLayout mDrawerLayout;

	private ListView mDrawerList;

	private ActionBarDrawerToggle mDrawerToggle;

	private CharSequence mDrawerTitle;

	private CharSequence mTitle;

	private MainMenuItem mSelectedMenuItem = null;

	private ArrayList<DrawerListItem> mDrawerItems;

	private boolean mServiceBound = false;

	private ProfileManager mProfileManager;

	private Fragment rootFragment;

	/**
	 * Connection to bind the background service
	 * 
	 * @see de.tudarmstadt.informatik.hostage.Hostage
	 */
	private ServiceConnection mConnection = new ServiceConnection() {
		/**
		 * After the service is bound, check which has been clicked and start
		 * it.
		 * 
		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName,
		 *      android.os.IBinder)
		 */
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mHoneyService = ((Hostage.LocalBinder) service).getService();
			mServiceBound = true;
		}

		/**
		 * After the service is unbound, delete reference.
		 * 
		 * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
		 */
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mHoneyService = null;
			mServiceBound = false;
		}

	};

	private HashMap<String, Boolean> mAttacksOnProtocol = new HashMap<String, Boolean>();

	private boolean mCloseWarning = false;

	/**
	 * Retrieve the singleton latest instance of the activity
	 * 
	 * @return MainActivity - the singleton instance
	 */
	public static MainActivity getInstance() {
		assert (sInstance != null);
		return sInstance;
	}

	public static Context getContext() {
		return MainActivity.context;
	}

	@Override
	public void onStart() {
		super.onStart();

		registerReceiver();

		if (isServiceRunning()) {
			this.bindService();
		}
	}

	@Override
	public void onStop() {
		this.unbindService();
		super.onStop();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		sInstance = this;
		MainActivity.context = getApplicationContext();

		setContentView(R.layout.activity_drawer_main);

		mProfileManager = ProfileManager.getInstance();

		ThreatIndicatorGLRenderer.assets = getAssets();
		ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING);
		// set background color
		TypedArray arr = getTheme().obtainStyledAttributes(new int[] { android.R.color.background_light });
		ThreatIndicatorGLRenderer.setBackgroundColor(arr.getColor(0, 0xFFFFFF));
		arr.recycle();

		ActionBar actionBar = getActionBar();
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP);

		mTitle = mDrawerTitle = getTitle();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);

		mDrawerItems = new ArrayList<DrawerListItem>();
		mDrawerItems.add(new DrawerListItem(R.string.drawer_overview, R.drawable.ic_menu_home));
		mDrawerItems.add(new DrawerListItem(R.string.drawer_threat_map, R.drawable.ic_menu_mapmode));
		mDrawerItems.add(new DrawerListItem(R.string.drawer_records, R.drawable.ic_menu_records));
		mDrawerItems.add(new DrawerListItem(R.string.drawer_statistics, R.drawable.ic_menu_stats));
		mDrawerItems.add(new DrawerListItem(R.string.drawer_services, R.drawable.ic_menu_set_as));
		mDrawerItems.add(new DrawerListItem(R.string.drawer_profile_manager, R.drawable.ic_menu_allfriends));
		mDrawerItems.add(new DrawerListItem(R.string.drawer_settings, R.drawable.ic_menu_preferences));
		mDrawerItems.add(new DrawerListItem(R.string.drawer_app_info, R.drawable.ic_menu_info_details));

		DrawerListAdapter listAdapter = new DrawerListAdapter(this, mDrawerItems);

		mDrawerList.setAdapter(listAdapter);
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setDisplayShowHomeEnabled(true);

		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
		mDrawerLayout, /* DrawerLayout object */
		R.drawable.ic_navigation_drawer, /*
										 * nav drawer image to replace 'Up'
										 * caret
										 */
		R.string.drawer_open, /* "open drawer" description for accessibility */
		R.string.drawer_close /* "close drawer" description for accessibility */
		) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		startAndBind();

		if (savedInstanceState == null) {
			// on first time display view for first nav item
			displayView(0);
		}
	}

	private void registerReceiver() {
		LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
	}

	private void unregisterReceiver() {
		LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
	}

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle extras = intent.getExtras();

			String sender = extras.getString("SENDER");
			String[] values = extras.getStringArray("VALUES");

			if (sender.equals(Hostage.class.getName()) && values[0].equals(getString(R.string.broadcast_started))) {
				mAttacksOnProtocol.put(values[1], true);
			}
		}
	};

	public boolean hasProtocolAttacks(String protocol) {
		if (!mAttacksOnProtocol.containsKey(protocol))
			return false;

		return mAttacksOnProtocol.get(protocol);
	}

	public void startAndBind() {
		if (!isServiceRunning()) {
			startService(getServiceIntent());
		}

		bindService();
	}

	public void stopAndUnbind() {
		if (mHoneyService != null) {
			unbindService();
		}

		stopService(getServiceIntent());
	}

	public void unbindService() {
		try {
			unbindService(mConnection);
		} catch (IllegalArgumentException ex) {
			// somehow already unbound.
		}
	}

	public void bindService() {
		mAttacksOnProtocol.clear();
		bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
		// mServiceBound = true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// Unregister Broadcast Receiver
		unregisterReceiver();

		// Unbind running service
		if (!mHoneyService.hasRunningListeners()) {
			stopAndUnbind();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		String action = getIntent().getAction();

		if (action != null && action.equals("SHOW_HOME")) {
			/*if (this.mDisplayedFragment != null && !this.mDisplayedFragment.getClass().equals(HomeFragment.class)) {
				getFragmentManager().popBackStackImmediate(HomeFragment.class.getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
				displayView(MainMenuItem.HOME.getValue());

				getIntent().setAction(null);
			}*/
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// toggle nav drawer on selecting action bar app icon/title
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}

		if (item.getItemId() == android.R.id.home) {
			if (!mDrawerToggle.isDrawerIndicatorEnabled()) {
				navigateBack();
			}
		}

		return super.onOptionsItemSelected(item);
	}

	public void navigateBack(){
		if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment)) {
			mDrawerToggle.setDrawerIndicatorEnabled(true);
			return;
		}

		UpNavigatibleFragment upNav = (UpNavigatibleFragment) this.mDisplayedFragment;

		getFragmentManager().popBackStackImmediate(upNav.getUpFragment().getName(), 0);
		this.mDisplayedFragment = getFragmentManager().findFragmentById(R.id.content_frame);
		configureFragment();

		if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment) || !((UpNavigatibleFragment) this.mDisplayedFragment).isUpNavigatible()) {
			mDrawerToggle.setDrawerIndicatorEnabled(true);
		} else {
			mDrawerToggle.setDrawerIndicatorEnabled(false);
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	public Fragment getCurrentFragment() {
		return this.mDisplayedFragment;
	}

	public void setDrawerIndicatorEnabled(boolean val) {
		mDrawerToggle.setDrawerIndicatorEnabled(val);
	}

	public void displayView(int position) {
		MainMenuItem menuItemPosition = MainMenuItem.create(position);

		if (this.mDisplayedFragment != null && this.mDisplayedFragment.getClass() == menuItemPosition.getKlass()) {
			mDrawerLayout.closeDrawer(mDrawerList);
			return;
		}

		Fragment fragment = null;

		try {
			fragment = (Fragment) menuItemPosition.getKlass().newInstance();
		} catch (InstantiationException e) {
			Log.i(menuItemPosition.getKlass().toString(), "Could not create new instance of fragment");
		} catch (IllegalAccessException e) {
			Log.i(menuItemPosition.getKlass().toString(), "Could not create new instance of fragment");
		}

		if (fragment != null) {
			if(position == 0 && rootFragment == null){
				rootFragment = fragment;
			}

			boolean isFirst = getFragmentManager().getBackStackEntryCount() == 0;

			//getFragmentManager().popBackStackImmediate(HomeFragment.class.getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
			// update selected item and title, then close the drawer if needed
			//if(!(fragment instanceof HomeFragment) || isFirst) {
				injectFragment(fragment);// , false, menuItemPosition);
			//} else {
			//	injectFragment(rootFragment);
			//}

			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(mDrawerItems.get(position).text);
		}

		mDrawerLayout.closeDrawer(mDrawerList);
	}

	public void injectFragment(Fragment fragment, boolean enableBack) {
		injectFragment(fragment);
	}

	public void injectFragment(Fragment fragment) {
		this.mCloseWarning = false;

		// set orientation fixed to portrait in home fragment
		if (fragment instanceof UpNavigatibleFragment) {
			UpNavigatibleFragment upFrag = (UpNavigatibleFragment) fragment;
			if (upFrag.getUpFragment() == null) {
				upFrag.setUpFragment(this.mDisplayedFragment.getClass());
			}
			if (upFrag.isUpNavigatible()) {
				mDrawerToggle.setDrawerIndicatorEnabled(false);
			}
		}

		configureFragment(fragment);

		FragmentManager fragmentManager = getFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
		fragmentTransaction.replace(R.id.content_frame, fragment, fragment.getClass().getName());
		fragmentTransaction.addToBackStack(fragment.getClass().getName());

		fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		fragmentTransaction.commit();

		this.mDisplayedFragment = fragment;
	}

	private void configureFragment() {
		configureFragment(this.mDisplayedFragment);
	}

	private void configureFragment(Fragment fragment) {
		if (fragment == null)
			return;

		if (fragment instanceof HomeFragment || fragment instanceof AboutFragment) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT | ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
		} else {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
		}

		if (fragment instanceof StatisticsFragment || fragment instanceof RecordOverviewFragment) {

			Intent intent = this.getIntent();
			intent.removeExtra(LogFilter.LOG_FILTER_INTENT_KEY);
		}
	}

	@Override
	public void onBackPressed() {
		if (mDisplayedFragment instanceof HomeFragment) {

			if (this.mCloseWarning) {
				MainActivity.getInstance().getHostageService().stopListeners();
				MainActivity.getInstance().stopAndUnbind();
				this.mCloseWarning = false;
				finish();
			} else {
				Toast.makeText(this, "Press the back button again to close HosTaGe", Toast.LENGTH_SHORT).show();
				this.mCloseWarning = true;
			}
			//}
		} else {
			super.onBackPressed();
			this.mDisplayedFragment = getFragmentManager().findFragmentById(R.id.content_frame);
			configureFragment();

			if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment) || !((UpNavigatibleFragment) this.mDisplayedFragment).isUpNavigatible()) {
				mDrawerToggle.setDrawerIndicatorEnabled(true);
			} else {
				mDrawerToggle.setDrawerIndicatorEnabled(false);
			}
		}
	}

	@Override
	public boolean onKeyDown(int keycode, KeyEvent e) {
		switch (keycode) {
		case KeyEvent.KEYCODE_MENU:
			if (this.mDrawerToggle.isDrawerIndicatorEnabled()) {
				if (this.mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
					this.mDrawerLayout.closeDrawer(Gravity.LEFT);
					return true;
				}
				this.mDrawerLayout.openDrawer(Gravity.LEFT);
			}
			return true;
		}

		return super.onKeyDown(keycode, e);
	}

	public Intent getServiceIntent() {
		return new Intent(this, Hostage.class);
	}

	public Fragment getDisplayedFragment() {
		return this.mDisplayedFragment;
	}

	public Hostage getHostageService() {
		return this.mHoneyService;
	}

	public boolean isServiceBound() {
		return this.mServiceBound;
	}

	public boolean isServiceRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
			if (service.service.getClassName().equals(Hostage.class.getName())) {
				return true;
			}
		}
		return false;
	}

	public void startMonitorServices(List<String> protocols){
		for(String protocol: protocols){
			if(protocol.equals("GHOST")){
				if(mProfileManager.getCurrentActivatedProfile() != null){
					Profile profile = mProfileManager.getCurrentActivatedProfile();
					if(profile.mGhostActive){
						for(int port: profile.getGhostPorts()){
							if(!getHostageService().isRunning(protocol, port)) getHostageService().startListener(protocol, port);
						}
					}
				}
			} else {
				if(!getHostageService().isRunning(protocol)) getHostageService().startListener(protocol);
			}
		}
	}

	public enum MainMenuItem {
		HOME(0, HomeFragment.class),
		THREAT_MAP(1, ThreatMapFragment.class),
		RECORDS(2, RecordOverviewFragment.class),
		STATISTICS(3, StatisticsFragment.class),
		SERVICES(4, ServicesFragment.class),
		PROFILE_MANAGER(5, ProfileManagerFragment.class),
		SETTINGS(6, SettingsFragment.class),
		APPLICATION_INFO(7, AboutFragment.class);

		private int value;
		private Class<?> klass;

		private MainMenuItem(int value, Class<?> klass) {
			this.value = value;
			this.klass = klass;
		}

		static public MainMenuItem create(int value) {
			if (value < 0 || value >= MainMenuItem.values().length)
				return MainMenuItem.HOME;
			return MainMenuItem.values()[value];
		}

		public static boolean hasClass(Class<?> klass){
			for(MainMenuItem m: MainMenuItem.values()){
				if(m.getKlass().equals(klass)) return true;
			}

			return false;
		}

		public int getValue() {
			return value;
		}

		public Class<?> getKlass() {
			return this.klass;
		}
	}

	private class DrawerItemClickListener implements ListView.OnItemClickListener {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			displayView(position);
		}
	}
}
