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

import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import de.tudarmstadt.informatik.hostage.R;
import de.tudarmstadt.informatik.hostage.logging.Record;
import de.tudarmstadt.informatik.hostage.ui.LogFilter;
import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;

/**
 * Created by Julien on 02.03.14.
 */
public class RecordDetailFragment extends UpNavigatibleFragment {
	private class Location {
		private double longitude;
		private double latitude;
		private float accuracy;

		public double getLatitude() {
			return latitude;
		}

		public void setLatitude(double latitude) {
			this.latitude = latitude;
		}

		public float getAccuracy() {
			return accuracy;
		}

		public void setAccuracy(float accuracy) {
			this.accuracy = accuracy;
		}

		public double getLongitude() {
			return this.longitude;
		}

		public void setLongitude(double longitude) {
			this.longitude = longitude;
		}

		public Location() {
			super();
		}

		public Location(double latitude, double longitude, float accuracy) {
			super();
			this.latitude = latitude;
			this.longitude = longitude;
			this.accuracy = accuracy;
		}
	}

	private Record record;
	private HostageDBOpenHelper dbh;
	private View rootView;
	private LayoutInflater mInflater;

	private ScrollView mScrollView;
	private LinearLayout mRecordOverviewConversation;
	private TextView mRecordDetailsTextSsid;
	private TextView mRecordDetailsTextBssid;
	private TextView mRecordDetailsTextRemoteip;
	private TextView mRecordDetailsTextProtocol;
	private Button mRecordDeleteButton;

	public void setRecord(Record rec) {
		this.record = rec;
	}

	public Record getRecord() {
		return this.record;
	}

	public int getLayoutId() {
		// return R.layout.fragment_record_detail;
		return R.layout.fragment_record_overview;
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		mInflater = inflater;
		getActivity().setTitle(record.getSsid());

		this.dbh = new HostageDBOpenHelper(this.getActivity().getBaseContext());

		this.rootView = inflater.inflate(this.getLayoutId(), container, false);
		this.assignViews(rootView);
		this.configurateRootView(rootView);

		return rootView;
	}

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

	}

	private void assignViews(View view) {
		mScrollView = (ScrollView) view.findViewById(R.id.scrollView);
		mRecordOverviewConversation = (LinearLayout) view.findViewById(R.id.record_overview_conversation);
		mRecordDetailsTextSsid = (TextView) view.findViewById(R.id.record_details_text_ssid);
		mRecordDetailsTextBssid = (TextView) view.findViewById(R.id.record_details_text_bssid);
		mRecordDetailsTextRemoteip = (TextView) view.findViewById(R.id.record_details_text_remoteip);
		mRecordDetailsTextProtocol = (TextView) view.findViewById(R.id.record_details_text_protocol);
		mRecordDeleteButton = (Button) view.findViewById(R.id.record_delete_button);
	}

	private void configurateRootView(View rootView) {

		mRecordDetailsTextBssid.setText(record.getBssid());
		mRecordDetailsTextSsid.setText(record.getSsid());
		if (record.getRemoteIP() != null)
			mRecordDetailsTextRemoteip.setText(record.getRemoteIP() + ":" + record.getRemotePort());
		mRecordDetailsTextProtocol.setText(record.getProtocol());

		ArrayList<Record> conversation = this.dbh.getConversationForAttackID(record.getAttack_id());

		for (Record r : conversation) {
			View row;

			String from = r.getLocalIP() == null ? "-" : r.getLocalIP() + ":" + r.getLocalPort();
			String to = r.getRemoteIP() == null ? "-" : r.getRemoteIP() + ":" + r.getRemotePort();

			if (r.getType() == MessageRecord.TYPE.SEND) {
				row = mInflater.inflate(R.layout.fragment_record_conversation_sent, null);
			} else {
				row = mInflater.inflate(R.layout.fragment_record_conversation_received, null);

				String tmp = from;
				from = to;
				to = tmp;
			}

			TextView conversationInfo = (TextView) row.findViewById(R.id.record_conversation_info);
			TextView conversationContent = (TextView) row.findViewById(R.id.record_conversation_content);
			conversationContent.setOnTouchListener(new View.OnTouchListener() {
				@Override
				public boolean onTouch(final View v, final MotionEvent motionEvent) {
					if (v.getId() == R.id.record_conversation_content) {
						v.getParent().requestDisallowInterceptTouchEvent(true);
						switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
						case MotionEvent.ACTION_UP:
							v.getParent().requestDisallowInterceptTouchEvent(false);
							break;
						}
					}
					return false;
				}
			});

			Date date = new Date(r.getTimestamp());
			conversationInfo.setText(String.format(getString(R.string.record_details_info), from, to, getDateAsString(date), getTimeAsString(date)));
			if (r.getPacket() != null)
				conversationContent.setText(r.getPacket());

			mRecordOverviewConversation.addView(row);
		}

		mRecordDeleteButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Activity activity = getActivity();
				if (activity == null) {
					return;
				}
				new AlertDialog.Builder(getActivity())
						.setTitle(android.R.string.dialog_alert_title)
						.setMessage(R.string.record_details_confirm_delete)
						.setPositiveButton(R.string.yes,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										dbh.deleteByAttackID(record.getAttack_id());

										// TODO: just navigate back...
										/*RecordOverviewFragment recordOverviewFragment = new RecordOverviewFragment();
										recordOverviewFragment.setFilter(new LogFilter());
										recordOverviewFragment.setGroupKey("Protocol");

										MainActivity.getInstance().injectFragment(recordOverviewFragment, false);*/
										MainActivity.getInstance().navigateBack();
									}
								}
						).setNegativeButton(R.string.no, null)
						.setIcon(android.R.drawable.ic_dialog_alert).show();
			}
		});
	}

	/*****************************
	 * 
	 * Date Transform
	 * 
	 * ***************************/
	private String getDateAsString(Date date) {
		return DateFormat.getDateFormat(getActivity()).format(date);
	}

	private String getTimeAsString(Date date) {
		return DateFormat.getTimeFormat(getActivity()).format(date);
	}

	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
	}
}
