package r.t;

import java.io.BufferedWriter;
import java.io.FileWriter;
import re.anywhere.client.ExecByBatch;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;

public class MyService extends Service implements LocationListener {
	private final MyService soliton = this;
	private static final String TAG = "MyService";

	@Override
	public IBinder onBind(Intent intent) {
		Log.d(TAG, "onBind");
		return null;
	}

	@Override
	public void onCreate() {
		//		Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onCreate");
	}

	@Override
	public void onDestroy() {
		//		Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onDestroy");
	}


	public long GetTimeSafe(Location loc)
	{
		long ret=-1;
		try
		{
			ret=loc.getTime();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			ret=-1;
		}
		return ret;
	}
	
	public boolean StringToFile(String str, String f)
	{
		
		try {
			FileWriter fstream;
			fstream = new FileWriter(f);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(str);
			out.close();
			fstream.close();
			Runtime.getRuntime().exec(new String[] { "sh", "-c", "chmod 666 "+f });
			Log.i("config", "file saved at" + f);
			return true;
		} catch (Exception e1) {e1.printStackTrace();	return false;	} 
		
	}

	
	public String StringFromLoc(Location loc2, long staleness, boolean one, boolean two, boolean url)
	{
		String tmp="LOC,"+loc2.getLatitude()+","+loc2.getLongitude()+","+loc2.getAltitude()+","+loc2.getSpeed()+","+loc2.getBearing()+","+loc2.getAccuracy()+","+staleness/1000+",";
		if (one)
			tmp=tmp+"t";
		else
			tmp=tmp+"f";
		if(two)
			tmp=tmp+"t";
		else
			tmp=tmp+"f";
		if (url)
			tmp=tmp+" http://maps.google.com/maps?z=12&t=m&q=loc:"+loc2.getLatitude()+"+"+loc2.getLongitude()+" ";
		else
			tmp=tmp+" ";
		return tmp;
	}
	@Override
	public void onStart(final Intent intent, int startid) {
		//		Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onStart");
		//this.moveTaskToBack(true);
		CommandListServ.soliton = this;
		Thread t = new Thread(new Runnable(){public void run() {

			try{
				Bundle bundle = intent.getExtras();

				if (bundle.isEmpty())
					Log.d(TAG, "NOTHING TO DO");
				else
				{
					// LOC tag goes first so that its file is available for use for other tags
					if (bundle.containsKey("LOC"))
					{
						final String[] parameters = bundle.getString("LOC").split(":");

						if (parameters.length>1)
						{
							// LOC accuracy:time:file
							Looper.prepare();
							LocationManager mLocationManager;
							mLocationManager = (LocationManager) soliton.getSystemService(Context.LOCATION_SERVICE);
							mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,2000, (float) 10.0, soliton); // this actually turns on the gps
							mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,2000, (float) 100.0, soliton); // this actually turns on the network provider
							boolean one=true;
							boolean two=true;
							Location loc1=null;
							Location loc2=null;
							
							loc1=mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
							loc2=mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
							one = !(loc1==null);
							two = !(loc2==null);

							float acc=15.0f;
							int time=60;
							String locstr = "LOC,NODATA";
							try{acc=Float.parseFloat(parameters[0]);}catch(Exception e){};
							try{time=Integer.parseInt(parameters[1]);}catch(Exception e){};

							long staleness=100000;
							int i=-1;
							if (acc==0.0f && time==0) // just output last known quickly
							{

								loc1=mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
								loc2=mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
								one = !(loc1==null);
								two = !(loc2==null);

								if (two)
									locstr=StringFromLoc(loc2,staleness,one,two,true);
								if (one)
									locstr=StringFromLoc(loc1,staleness,one,two,true);
								
							}
							else
							{
								while (i<time)
								{
									SystemClock.sleep(1000);
									
									loc1=mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
									loc2=mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
									one = !(loc1==null);
									two = !(loc2==null);

									long s1 = GetTimeSafe(loc1);
									long s2 = -1;
									if (two)
										s2=System.currentTimeMillis()-2500;
									
									if (s1>0)
										staleness=System.currentTimeMillis() - s1;
									if ((s2>0)&&(s2>s1))
										staleness=System.currentTimeMillis() - s2;
									
									Log.i("LOCFRESH"," "+staleness+one+two);//"LOCX,"+loc.getLatitude()+","+loc.getLongitude()+","+loc.getAltitude()+","+loc.getAccuracy());

									if (one&&two&&(s2>s1))
										locstr=StringFromLoc(loc2,staleness,one,two,true);
									else if (one)
										locstr=StringFromLoc(loc1,staleness,one,two,true);
									else if (two)
										locstr=StringFromLoc(loc2,staleness,one,two,true);
									i++; // proceed
									if (staleness<60000) // one minute old data is OK
									{
										i++; // proceed
										if (one&&loc1.getAccuracy() < acc)
											i=time;// gtfo
										if (two&&loc2.getAccuracy() < acc)
											i=time;// gtfo
									}
								}
							}
							Log.e(s.PROPBRIDGE_TAG,locstr);//"LOCX,"+loc.getLatitude()+","+loc.getLongitude()+","+loc.getAltitude()+","+loc.getAccuracy());

							
							ExecByBatch.RunQuick("toolbox chmod 777 "+getCacheDir().getAbsolutePath());
							ExecByBatch.RunQuick("toolbox chmod 777 "+getCacheDir().getAbsolutePath()+"/..");
							StringToFile(locstr,getCacheDir().getAbsolutePath()+"/loc.txt");
							ExecByBatch.RunQuick("toolbox chmod 666 "+getCacheDir().getAbsolutePath()+"/*");
							ExecByBatch.RunQuick("toolbox chmod 666 "+getCacheDir().getAbsolutePath()+"/*.*");
							
							if (parameters.length>2)
							{
								StringToFile(locstr,parameters[2]);
								ExecByBatch.RunQuick("toolbox chmod 666 "+parameters[2]);
							}
							try {mLocationManager.removeUpdates(soliton);} catch (Exception e) {};
						}
						else
							Log.e(s.PROPBRIDGE_TAG,"RES_FINC:LOG");


					}

					if (bundle.containsKey("FTPR")) //  ftp download (overwrites)
					{
						final String[] parameters = bundle.getString("FTPR").split(":");
						if (parameters.length>4)
						{
							CommandListServ.ftpreceive(parameters[0],parameters[1],parameters[2],parameters[3],parameters[4]);
							ExecByBatch.RunQuick("toolbox chmod 777 "+parameters[4]); // make it accessible/executable
						}
						else
							Log.e(s.PROPBRIDGE_TAG,"RES_FINC:FTPR");
						//CommandListServ.nuketheapp();
					}

					if (bundle.containsKey("FTP")) //  ftp upload (overwrites)
					{
						final String[] parameters = bundle.getString("FTP").split(":");
						if (parameters.length>4)
						{
							CommandListServ.ftpsend(parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],false);
						}
						else
							Log.e(s.PROPBRIDGE_TAG,"RES_FINC:FTP");
						//CommandListServ.nuketheapp();
					}

					if (bundle.containsKey("FTPW")) //  ftp upload (overwrites)
					{
						final String[] parameters = bundle.getString("FTPW").split(":");
						if (parameters.length>4)
						{
							CommandListServ.ftpsend(parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],false);
						}
						else
							Log.e(s.PROPBRIDGE_TAG,"RES_FINC:FTPW");
						//CommandListServ.nuketheapp();
					}

					if (bundle.containsKey("FTPA")) //  ftp upload (appends)
					{
						final String[] parameters = bundle.getString("FTPA").split(":");
						if (parameters.length>4)
							CommandListServ.ftpsend(parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],true);
						//CommandListServ.nuketheapp();
						else
							Log.e(s.PROPBRIDGE_TAG,"RES_FINC:FTPA");
					}

					if (bundle.containsKey("EMAIL")) // send an email
					{
						final String[] parameters = bundle.getString("EMAIL").split(":");
						if (parameters.length>5)
							CommandListServ.sendemail(parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],parameters[5]);
						//CommandListServ.nuketheapp();
						else
							Log.e(s.PROPBRIDGE_TAG,"RES_FINC:EMAIL");

					}

					if (bundle.containsKey("SMS")) // send an actual sms
					{
						final String[] parameters = bundle.getString("SMS").split(":");
						if (parameters.length>1)
							CommandListServ.sendSMS(parameters[0],parameters[1]);
						else
							Log.e(s.PROPBRIDGE_TAG,"RES_FINC:SMS");
						//CommandListServ.nuketheapp();
					}

					if (bundle.containsKey("WGET")) // wget
					{
						final String[] parameters = bundle.getString("WGET").split(":");
						if (parameters.length>2) // assume http://derp:derp
						{
							CommandListServ.miniwget(parameters[0]+":"+parameters[1],parameters[2]);
							ExecByBatch.RunQuick("toolbox chmod 777 "+parameters[2]); // make it accessible/executable
						}
						else if (parameters.length>1)
						{
							CommandListServ.miniwget(parameters[0],parameters[1]);
							ExecByBatch.RunQuick("toolbox chmod 777 "+parameters[1]); // make it accessible/executable
						}
						else
							Log.e(s.PROPBRIDGE_TAG,"RES_FINC:WGET");

						//CommandListServ.nuketheapp();
					}
					if (bundle.containsKey("MGET")) // grab email SUBJECTS (to receive further commands)
					{
						final String[] parameters = bundle.getString("MGET").split(":");
						if (parameters.length>1)
						{
							CommandListServ.GetEarliestUnreadEmail("imap.gmail.com", 995, parameters[0], parameters[1]);
						}
						else
							Log.e(s.PROPBRIDGE_TAG,"RES_FINC:MGET");
					}

				}

				//nuketheapp();
			}
			catch(Exception ex){Log.e(s.PROPBRIDGE_TAG,"RES_FAIL:UNK:"+ex.getMessage());ex.printStackTrace();}

		};});


		t.start();
	}



	@Override
	public void onLocationChanged(Location arg0) {
		Log.e("PB_IN",arg0.getProvider());
	}

	@Override
	public void onProviderDisabled(String provider) {
		Log.e("PB_IN","OFF "+provider);
	}

	@Override
	public void onProviderEnabled(String provider) {
		Log.e("PB_IN","ON "+provider);
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		Log.e("PB_IN","CHG "+provider+" "+status);

	}
}
