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


import android.app.AlertDialog;
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.app.Fragment;
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.ListView;
import android.widget.Switch;
import android.widget.TextView;

import java.util.ArrayList;

import de.tudarmstadt.informatik.hostage.R;
import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
import de.tudarmstadt.informatik.hostage.logging.LogResultReceiver;
import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
import de.tudarmstadt.informatik.hostage.ui2.adapter.ServicesListAdapter;
import de.tudarmstadt.informatik.hostage.ui2.model.ServicesListItem;


/**
 * Created by Daniel Lazar on 05.02.14.
 */
public class ServicesFragment extends Fragment{

	private Switch mServicesSwitchService;
	private TextView mServicesTextName;

	private View rootView;

	private CompoundButton.OnCheckedChangeListener switchChangeListener = null;

	private BroadcastReceiver mReceiver;

	private ServicesListAdapter adapter;

	private ArrayList<ServicesListItem> protocolList;

	private UglyDbHelper dbh = new UglyDbHelper(MainActivity.getContext());

	private String[] protocols;

	private SharedPreferences mConnectionInfo;


	private void assignViews(){
		mServicesSwitchService = (Switch) rootView.findViewById(R.id.service_switch_connection);
		mServicesTextName = (TextView) rootView.findViewById(R.id.services_text_name);

		rootView.findViewById(R.id.services_button_connection_info).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ConnectionInfoDialogFragment connectionInfoDialogFragment = new ConnectionInfoDialogFragment();
				connectionInfoDialogFragment.show(getFragmentManager().beginTransaction(), connectionInfoDialogFragment.getTag());
			}
		});
	}

	public void updateUI(){
		if(!HelperUtils.isWifiConnected(getActivity())){
			mServicesSwitchService.setOnCheckedChangeListener(null);
			setStateNotConnected();
			setStateNotActive();
			mServicesSwitchService.setOnCheckedChangeListener(switchChangeListener);
		}
		else {
			mServicesTextName.setText(HelperUtils.getSSID(getActivity()));
		}

	}
	public ServicesFragment(){}

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

				for(int i = 0; i < protocols.length; i++ ){
					protocolList.get(i).attacks = String.valueOf(dbh.numBssidSeen(protocolList.get(i).protocol, mConnectionInfo.getString(getString(R.string.connection_info_bssid), null)));
				}
				if (!MainActivity.getInstance().getHoneyService().hasRunningListeners()) {
					setStateNotActive();
				}
				adapter.notifyDataSetChanged();
			}
		};

		LocalBroadcastManager
				.getInstance(getActivity()).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
	}

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

		super.onCreateView(inflater, container, savedInstanceState);

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

		protocols = getResources().getStringArray(R.array.protocols);
		mConnectionInfo = getActivity().getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);

		updateUI();

		ListView list = (ListView) rootView.findViewById(R.id.services_list_view);

		protocolList= new ArrayList<ServicesListItem>();

		for(String protocol: protocols){
			protocolList.add(new ServicesListItem(protocol));
			if(MainActivity.getInstance().getHoneyService().isRunning(protocol)){
				setStateActive();
			}
		}
		for(int i=0; i < protocols.length; i++){

			protocolList.get(i).attacks = String.valueOf(dbh.numBssidSeen(protocolList.get(i).protocol, mConnectionInfo.getString(getString(R.string.connection_info_bssid), null)));
		//	protocolList.get(i).initialValue = Integer.valueOf(protocolList.get(i).attacks);
		}
		adapter = new ServicesListAdapter(getActivity().getBaseContext(), protocolList);
		adapter.setActivity(this.getActivity(), this.mServicesSwitchService, this.switchChangeListener);
		list.setAdapter(adapter);

		registerBroadcastReceiver();

		mServicesSwitchService = (Switch) rootView.findViewById(R.id.service_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();
						}
					}
				}

			};
		}
		mServicesSwitchService.setOnCheckedChangeListener(switchChangeListener);



		return rootView;

	};

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

	@Override
	public void onStop(){
		super.onStop();
		unregisterBroadcastReceiver();

	}

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

	private void setStateActive() {
		mServicesSwitchService.setChecked(true);
	}

	private void setStateNotConnected() {
		mServicesTextName.setText(R.string.not_connected);
	}

	private void setStateNotActive() {
		mServicesSwitchService.setChecked(false);

	}

	@Override
	public void onDestroy(){
		super.onDestroy();
		LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
	}

}
