package com.microaiddreamworks.gps;

import com.microaiddreamworks.util.ServerMethods;
import com.skyhookwireless.wps.IPLocation;
import com.skyhookwireless.wps.IPLocationCallback;
import com.skyhookwireless.wps.Location;
import com.skyhookwireless.wps.WPSAuthentication;
import com.skyhookwireless.wps.WPSContinuation;
import com.skyhookwireless.wps.WPSLocation;
import com.skyhookwireless.wps.WPSLocationCallback;
import com.skyhookwireless.wps.WPSPeriodicLocationCallback;
import com.skyhookwireless.wps.WPSReturnCode;
import com.skyhookwireless.wps.WPSStreetAddressLookup;
import com.skyhookwireless.wps.XPS;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.ListPreference;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;


public class ThisGps extends Activity implements View.OnClickListener{
	ServerMethods mObjServerMethods = null;
	String m_clRetVal = null;
	private ImageButton img_Button = null;
	TextView myLocationText;
//	String checkLatLong;
	TextView status;

	private String _username = null, _realm = null;
	private long _period;
	private int _desiredXpsAccuracy;
	private XPS _xps;
	private Handler _handler;
	private boolean _stop;
	private ThisGps mThisGps;
	String getLatLng = "";
	private static final int LOCATION_MESSAGE = 1;
	private static final int ERROR_MESSAGE = 2;
	private static final int DONE_MESSAGE = 3;
	
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gps);
		

		img_Button = (ImageButton) findViewById(R.id.PANIC_BUTTON_IMG);
		img_Button.setBackgroundColor(Color.TRANSPARENT);
		img_Button.setFocusable(true);
		img_Button.setClickable(true);
		img_Button.setOnClickListener(this);
		View lViewSettng = findViewById(R.id.RELATIVE_SETTINGS);
		lViewSettng.setOnClickListener(this);
		// create the XPS instance, passing in our Context
		_xps = new XPS(this);
		_stop = false;
		setUIHandler();
		WPSAuthentication auth = new WPSAuthentication(_username, _realm);
		_xps.getXPSLocation(auth, (int) (_period / 1000), _desiredXpsAccuracy,_callback);
		saveLatLongPref(this, 3, getLatLng);
	}
	
	@Override
	public void onClick(View pView) {
		switch (pView.getId()) {
		case R.id.RELATIVE_SETTINGS:
			Intent lIntent = new Intent(this, PassCode.class);
			startActivity(lIntent);
			break;
		case R.id.PANIC_BUTTON_IMG:
			ImageButton lPanicText = (ImageButton) findViewById(R.id.PANIC_BUTTON_IMG);
			lPanicText.setVisibility(View.VISIBLE);
			PanicBtnData();
			break;
		}
	}
	
	private void PanicBtnData() {
		mObjServerMethods = new ServerMethods();
		TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		String imei = mTelephonyMgr.getDeviceId();
		String getUId = fetchUserIdPref(this, 2);
		m_clRetVal = mObjServerMethods.RequestPanicData(imei,(String) myLocationText.getText(), getUId);
		if (null == m_clRetVal)
			alertbox("Panic Button Info", "wrong data");
	}
	
	
	

	/**
	 * A single callback class that will be used to handle all notifications
	 * sent by WPS to our app.
	 */
	private class MyLocationCallback implements IPLocationCallback,WPSLocationCallback, WPSPeriodicLocationCallback {
	//	ThisGps mThisGps;

		/*MyLocationCallback(ThisGps pThisGps) {
			mThisGps = pThisGps;
		}
		*/
		
		

		public void done() {
			// tell the UI thread to re-enable the buttons
			_handler.sendMessage(_handler.obtainMessage(DONE_MESSAGE));
			

		}

		public WPSContinuation handleError(WPSReturnCode error) {
			// send a message to display the error
			_handler.sendMessage(_handler.obtainMessage(ERROR_MESSAGE, error));
			// return WPS_STOP if the user pressed the Stop button
			if (!_stop)
				return WPSContinuation.WPS_CONTINUE;
			else
				return WPSContinuation.WPS_STOP;
		}

		public void handleIPLocation(IPLocation location) {
			// send a message to display the location
			_handler.sendMessage(_handler.obtainMessage(LOCATION_MESSAGE,
					location));
			
		}

		public void handleWPSLocation(WPSLocation location) {
			// send a message to display the location
			_handler.sendMessage(_handler.obtainMessage(LOCATION_MESSAGE,
					location));

		}

		public WPSContinuation handleWPSPeriodicLocation(WPSLocation location) {
			_handler.sendMessage(_handler.obtainMessage(LOCATION_MESSAGE,
					location));
			// return WPS_STOP if the user pressed the Stop button
			if (!_stop)
				return WPSContinuation.WPS_CONTINUE;
			else
				return WPSContinuation.WPS_STOP;
		}

	}
	private final MyLocationCallback _callback = new MyLocationCallback();

	private void setUIHandler() {
		
		try{
	//	Toast.makeText(this, getLatLng, Toast.LENGTH_LONG).show();
		
//		Toast.makeText(this, getLatLng , Toast.LENGTH_LONG).show();
		
	 			_handler = new Handler() {
			
			public void handleMessage(final Message msg) {
				
				
		//		checkLatLong = myLocationText.getText().toString();
				
				switch (msg.what) {
				case LOCATION_MESSAGE:
					Location location = (Location) msg.obj;
			//		System.out.println(location);
					String getFullLocation = location.toString();
			//		System.out.println(getFullLocation);
					String tempLatLng = getFullLocation.substring(0,getFullLocation.toString().indexOf("+"));
					String[] splitChar = tempLatLng.split(",");
					getLatLng = splitChar[0].trim() + "," + splitChar[1].trim();
					TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
					String imei = mTelephonyMgr.getDeviceId();
					mObjServerMethods = new ServerMethods();
					String checkLatLong = fetchLatLongPref(mThisGps, 3);
				//	Toast.makeText(this, checkLatLong, Toast.LENGTH_LONG).show();
				//	System.out.println(checkLatLong);
					if (getLatLng != checkLatLong)
						mObjServerMethods.setLocation(imei,checkLatLong,getLatLng);
					    myLocationText.setText(getLatLng);
					    String getSpeed = getFullLocation.substring(getFullLocation.indexOf("+/-") + 3, getFullLocation.indexOf("0deg"));
					    status.setText(getSpeed);
					 //  saveData();
					return;
					
				/*case ERROR_MESSAGE:
					myLocationText.setText(((WPSReturnCode) msg.obj).name());
					
					return;*/
				
				}
				
			}
		};
		}catch(Exception pEx){
			System.out.println(pEx.toString());
				
			}
	}
	
	
	static String fetchUserIdPref(Context context, int key) {
		SharedPreferences prefs = context.getSharedPreferences("USERID", 0);
		String userId = prefs.getString("USERID" + key, null);
		return userId;
	}

	
	
		public void saveLatLongPref(Context context, int key, String slatLongValue) {
			SharedPreferences.Editor prefs = context.getSharedPreferences("LATLONG", 0).edit();
			prefs.putString("LATLONG" + key, slatLongValue);
//			prefs.remove(slatLongValue);
			prefs.commit();

		}

		public String fetchLatLongPref(Context context, int key) {
			SharedPreferences prefs = context.getSharedPreferences("LATLONG", 0);
			String slatLong = prefs.getString("LATLONG" + key, null);
			Toast.makeText(mThisGps, slatLong, Toast.LENGTH_LONG).show();
			if (slatLong != null) {
				return slatLong;
			} else {
				return null;
			}
		}

		protected void alertbox(String title, String mymessage) {
			new AlertDialog.Builder(this).setMessage(mymessage).setTitle(title)
					.setCancelable(true).setNeutralButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									if (null != m_clRetVal) {
										Intent btnIntent = new Intent();
										btnIntent.setClass(ThisGps.this,
												ThisGps.class);
										startActivity(btnIntent);
									}
								}
							}).show();
		}
}