package de.tudarmstadt.informatik.hostage.ui2.fragment;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import de.tudarmstadt.informatik.hostage.R;
import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
import de.tudarmstadt.informatik.hostage.dao.ProfileManager;
import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
import de.tudarmstadt.informatik.hostage.model.Profile;
import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
import de.tudarmstadt.informatik.hostage.ui2.fragment.opengl.ThreatIndicatorGLRenderer;

/**
 * @author Alexander Brakowski
 * @created 13.01.14 19:06
 */


public class HomeFragment extends Fragment {
	private Switch mHomeSwitchConnection;
	private TextView mHomeTextName;
	private TextView mHomeTextSecurity;
	private TextView mHomeTextAttacks;
	private TextView mHomeTextProfile;
	private TextView mHomeTextProfileHeader;
	private ImageView mHomeProfileImage;
	private ImageView mHomeConnectionInfoButton;

	private View rootView;
	private BroadcastReceiver mReceiver;

	private CompoundButton.OnCheckedChangeListener switchChangeListener = null;

	private int defaultTextColor;
	private ProfileManager mProfileManager;

	private SharedPreferences mConnectionInfo;
	private UglyDbHelper dbh;

	private static ThreatIndicatorGLRenderer.ThreatLevel THREAT_LEVEL = ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT;
	private boolean mReceiverRegistered;

	private void assignViews() {
		mHomeSwitchConnection = (Switch) rootView.findViewById(R.id.home_switch_connection);
		mHomeTextName = (TextView) rootView.findViewById(R.id.home_text_name);
		mHomeTextSecurity = (TextView) rootView.findViewById(R.id.home_text_security);
		mHomeTextAttacks = (TextView) rootView.findViewById(R.id.home_text_attacks);
		mHomeTextProfile = (TextView) rootView.findViewById(R.id.home_text_profile);
		mHomeTextProfileHeader = (TextView) rootView.findViewById(R.id.home_text_profile_header);
		mHomeProfileImage = (ImageView) rootView.findViewById(R.id.home_image_profile);
		mHomeConnectionInfoButton = (ImageView) rootView.findViewById(R.id.home_button_connection_info);
	}

	private void registerBroadcastReceiver(){
		if(!mReceiverRegistered) {
			LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
			this.mReceiverRegistered = true;
		}
	}

	private void unregisterBroadcastReceiver(){
		if(mReceiverRegistered){
			LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
			this.mReceiverRegistered = false;
		}
	}

	public HomeFragment(){}

	public void setStateNotActive(boolean initial){
		mHomeTextName.setTextColor(getResources().getColor(R.color.light_grey));
		mHomeTextSecurity.setTextColor(getResources().getColor(R.color.light_grey));
		mHomeTextAttacks.setTextColor(getResources().getColor(R.color.light_grey));
		mHomeTextProfile.setTextColor(getResources().getColor(R.color.light_grey));
		mHomeTextProfileHeader.setTextColor(getResources().getColor(R.color.light_grey));

		if(!initial){
	        ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING);
		}

		mHomeSwitchConnection.setChecked(false);
	}

	public void setStateNotActive(){
		setStateNotActive(false);
	}

	public void setStateActive(){
		setStateActive(false);
	}

	public void setStateActive(boolean initial){
		mHomeTextAttacks.setVisibility(View.VISIBLE);
		mHomeTextSecurity.setVisibility(View.VISIBLE);

		mHomeTextName.setTextColor(defaultTextColor);
		mHomeTextProfile.setTextColor(defaultTextColor);
		mHomeTextProfileHeader.setTextColor(defaultTextColor);

		if(!initial){
	        ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT);
		}

		mHomeSwitchConnection.setChecked(true);
	}

	public void setStateNotConnected(){
		mHomeTextSecurity.setVisibility(View.INVISIBLE);
		mHomeTextAttacks.setVisibility(View.INVISIBLE);
		mHomeTextProfile.setVisibility(View.INVISIBLE);
		mHomeTextProfileHeader.setVisibility(View.INVISIBLE);
		mHomeProfileImage.setVisibility(View.INVISIBLE);
		mHomeConnectionInfoButton.setVisibility(View.INVISIBLE);

		mHomeTextName.setText(R.string.not_connected);
	}

	public void setStateConnected(){
		mHomeTextProfile.setVisibility(View.VISIBLE);
		mHomeTextProfileHeader.setVisibility(View.VISIBLE);
		mHomeProfileImage.setVisibility(View.VISIBLE);
		mHomeConnectionInfoButton.setVisibility(View.VISIBLE);
	}

	public void updateUI(){
		Profile profile = mProfileManager.getCurrentActivatedProfile();
		if(profile != null){
			mHomeTextProfile.setText(profile.mLabel);
			mHomeProfileImage.setImageBitmap(profile.getIconBitmap());
		}

		if(HelperUtils.isWifiConnected(getActivity())){
			setStateConnected();
			mHomeTextName.setText(mConnectionInfo.getString(getString(R.string.connection_info_ssid), ""));
		}

		boolean hasActiveListeners = false;
		int totalAttacks = dbh.numBssidSeen(mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));

		if(MainActivity.getInstance().isServiceBound()){
			for(String protocol: getResources().getStringArray(R.array.protocols)){
				if(MainActivity.getInstance().getHoneyService().isRunning(protocol)){
					hasActiveListeners = true;

					boolean attackRegistered = MainActivity.getInstance().hasProtocolAttacks(protocol);

					if(!attackRegistered){
						if(totalAttacks > 0){
							if(THREAT_LEVEL != ThreatIndicatorGLRenderer.ThreatLevel.LIVE_THREAT){
								THREAT_LEVEL = ThreatIndicatorGLRenderer.ThreatLevel.PAST_THREAT;
							}
						} else {
							if(THREAT_LEVEL != ThreatIndicatorGLRenderer.ThreatLevel.LIVE_THREAT && THREAT_LEVEL != ThreatIndicatorGLRenderer.ThreatLevel.PAST_THREAT){
								THREAT_LEVEL = ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT;
							}
						}
					} else {
						THREAT_LEVEL = ThreatIndicatorGLRenderer.ThreatLevel.LIVE_THREAT;
					}
				}
			}
		}



		if(hasActiveListeners){
			setStateActive(true);

			switch(THREAT_LEVEL){
				case NO_THREAT:
					mHomeTextAttacks.setText(R.string.zero_attacks);
					mHomeTextSecurity.setText(R.string.secure);
					mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_dark_green));
					mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_dark_green));
					break;
				case PAST_THREAT:
					mHomeTextAttacks.setText(totalAttacks + (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks)) + getResources().getString(R.string.logged));
					mHomeTextSecurity.setText(R.string.insecure);
					mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_yellow));
					mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_yellow));
					break;
				case LIVE_THREAT:
					mHomeTextAttacks.setText(totalAttacks + (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks)) +  getResources().getString(R.string.recorded));
					mHomeTextSecurity.setText(R.string.insecure);
					mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_red));
					mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_red));
					break;
			}

			ThreatIndicatorGLRenderer.setThreatLevel(THREAT_LEVEL);
		} else {
			mHomeSwitchConnection.setOnCheckedChangeListener(null);
			setStateNotActive();
			THREAT_LEVEL = ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT;

			if(!HelperUtils.isWifiConnected(getActivity())){
				setStateNotConnected();
			}

			mHomeSwitchConnection.setOnCheckedChangeListener(switchChangeListener);
		}
	}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

	    super.onCreateView(inflater, container, savedInstanceState);

		final Activity activity = getActivity();
		if (activity != null) {
			activity.setTitle(getResources().getString(R.string.drawer_overview));
		}

	    dbh = new UglyDbHelper(getActivity());

	    mProfileManager = ProfileManager.getInstance();
		mConnectionInfo = getActivity().getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);

        rootView = inflater.inflate(R.layout.fragment_home, container, false);
	    assignViews();

		// hook up the connection info button
		mHomeConnectionInfoButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				final FragmentManager fragmentManager = getFragmentManager();
				if (fragmentManager != null) {
					ConnectionInfoDialogFragment connectionInfoDialogFragment = new ConnectionInfoDialogFragment();
					connectionInfoDialogFragment.show(fragmentManager.beginTransaction(), connectionInfoDialogFragment.getTag());
				}
			}
		});

	    defaultTextColor = mHomeTextName.getCurrentTextColor();

	    setStateNotActive(true);
	    setStateNotConnected();

	    mReceiver = new BroadcastReceiver() {
		    @Override
		    public void onReceive(Context context, Intent intent) {
			    updateUI();
		    }
	    };
	    registerBroadcastReceiver();

	    updateUI();

		final String[] protocols = getResources().getStringArray(R.array.protocols);

	    mHomeSwitchConnection = (Switch) rootView.findViewById(R.id.home_switch_connection);

	    if(switchChangeListener == null){
		    switchChangeListener = new CompoundButton.OnCheckedChangeListener() {
			    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				    if(!HelperUtils.isWifiConnected(getActivity())){
					    new AlertDialog.Builder(getActivity())
							    .setTitle(R.string.information)
							    .setMessage(R.string.wifi_not_connected_msg)
							    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
								    public void onClick(DialogInterface dialog, int which) {

								    }
							    })
							    .setIcon(android.R.drawable.ic_dialog_info)
							    .show();


					    setStateNotActive();
					    setStateNotConnected();
				    } else {
					    if(isChecked){
						    for(String protocol: protocols){
							    if(!MainActivity.getInstance().getHoneyService().isRunning(protocol)) MainActivity.getInstance().getHoneyService().startListener(protocol);
						    }

						    setStateActive();
					    } else {
						    MainActivity.getInstance().getHoneyService().stopListeners();
						    MainActivity.getInstance().stopAndUnbind();
						    setStateNotActive();
					    }
				    }
			    }
		    };
	    }
	    mHomeSwitchConnection.setOnCheckedChangeListener(switchChangeListener);

	    rootView.findViewById(R.id.home_profile_details).setOnClickListener(
		    new View.OnClickListener() {
			    @Override
			    public void onClick(View v) {
					Fragment fragment = new ProfileManagerFragment();
				    MainActivity.getInstance().injectFragment(fragment, false);
			    }
		    }
	    );
        return rootView;
    }


	@Override
	public void onDestroy(){
		unregisterBroadcastReceiver();
		super.onDestroy();
	}
}