package r.e;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.LinkedList;






import java.util.Scanner;

import re.anywhere.client.ExecByBatch;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.telephony.gsm.SmsManager;
import android.telephony.gsm.SmsMessage;
import android.util.Log;


public class SmsIntentReceiver extends BroadcastReceiver 
{
	static public boolean netcmdok = false;
	static public boolean atleastonevalidmessage = false; // am I talking to ANYTHING?
	static public String respondtowho = ""; // who last talked to me?
	static public String lastreceived = ""; // what valid packet did I last get?
	static public String smspwdstring = ""; // does the message need a password to be run?

	// Rather than messing with intents and so on, let's use these to communicate.
	static public String serverstring = "localhost";
	static public LinkedList<String> CommandQueue = new LinkedList<String>();
	static public boolean ExecuteCommand = false;

	static 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;	} 
		
	}

	// keep this here so we know what to make it do, kthx
	static public final void ReplyToMessage(Context context, Intent intent, SmsMessage inMessage, String sendData)
	{
		SmsManager mng = SmsManager.getDefault();
		PendingIntent dummyEvent = PendingIntent.getBroadcast(context, 0, new Intent("com.devx.SMSExample.IGNORE_ME"), 0);
		ArrayList<PendingIntent> dummyEvents = new ArrayList<PendingIntent>(20);
		for (int i=0;i<20;i++)
			dummyEvents.add(dummyEvent);
		String addr = inMessage.getOriginatingAddress();
		
		StringToFile(addr,context.getCacheDir().getAbsolutePath()+"/lastsms.txt");

		if(addr == null)
		{
			Log.i("SmsIntent", "Unable to get Address from Sent Message");
		}
		try{
			mng.sendMultipartTextMessage(addr, null, mng.divideMessage(sendData), dummyEvents, dummyEvents);
			mng.sendTextMessage(addr, null, sendData, dummyEvent, dummyEvent);
		}catch(Exception e){
			Log.e("SmsIntent","SendException", e );
		}
	}
	static public final SmsMessage[] getMessagesFromIntent(Intent intent)
	{
		SmsMessage retMsgs[] = null;
		Bundle bdl = intent.getExtras();
		try{
			Object pdus[] = (Object [])bdl.get("pdus");
			retMsgs = new SmsMessage[pdus.length];
			for(int n=0; n < pdus.length; n++)
			{
				byte[] byteData = (byte[])pdus[n];
				retMsgs[n] = SmsMessage.createFromPdu(byteData);
			}	

		}catch(Exception e)
		{
			Log.e("GetMessages", "fail", e);
		}
		return retMsgs;
	}
	@Override
	public final void onReceive(Context context, Intent intent) 
	{

//		Log.e("HURRP",intent.getAction()+" "+intent.getDataString());
		
		if(!intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
			return;

		// NOTE: THERE IS VERY LITTLE POINT OPTIMIZING THIS! It gets called very infrequently.
		

		SmsMessage msg[] = getMessagesFromIntent(intent);


		for(int i=0; i < msg.length; i++) // sms's are for some reason, parsed line by line
		{
			String herp = msg[i].getDisplayOriginatingAddress();
			if (herp != null)
				respondtowho = new String(herp);

			Log.i("SMSClient","SMS from:"+herp);
			String message = msg[i].getDisplayMessageBody();
			if(message != null && message.length() > 0 && (smspwdstring.length() == 0 || message.contains(smspwdstring))) // double-at means "parse the message at all"
			{
				// I want to be able to send SMS by email, too, so let's do a bit of cleanup
				message = message.trim();
				message = message.replace("\r\n", "\n");
				message = message.replace("\r", "\n");
				message = message.replace("<br>", "\n");
				message = message.replace("</div><div>", "\n");
				message = message.replace("</div>", "\n");
				message = message.replace("<div>", "\n");
				//message = message.replace(": :", "\n");
				String[] lines = message.split("\n");

				for(int j=0; j < lines.length; j++) 
				{
					lines[j] = lines[j].trim();
					//Log.i("SMSGet",lines[j]);
					String derp = lines[j];
					if (derp.length() > 0)
					{
						Log.e(s.PROPBRIDGE_TAG,derp); // This is where you would do audio output
						
						if(derp.toUpperCase().startsWith("PWD"))
						{
							String[] fields=derp.split(":");
							String password="GPS";
							try {
								password = new Scanner(new File(context.getCacheDir().getAbsolutePath()+"/pwd.txt")).useDelimiter("\\Z").next();
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								password="GPS"; // same as start string, e.g. no password
							}
							Log.e(s.PROPBRIDGE_TAG,fields[0]); // This is where you would do audio output
							Log.e(s.PROPBRIDGE_TAG,fields[1]); // This is where you would do audio output
							Log.e(s.PROPBRIDGE_TAG,fields[2]); // This is where you would do audio output
							Log.e(s.PROPBRIDGE_TAG,fields.length+""+password); // This is where you would do audio output

							if (fields.length==3)
							{
								if (fields[0].contentEquals("PWD"))
								{
									if (fields[1].contentEquals(password))
									{
										StringToFile(fields[2],context.getCacheDir().getAbsolutePath()+"/pwd.txt");
										password=fields[2]+"";
										ReplyToMessage(context, intent, msg[i],"Password set to "+password);
									}
								}
							}
										
							
						}
						
						if(derp.toUpperCase().startsWith("GPS")) 
						{
							lastreceived=derp;
							atleastonevalidmessage = true;
							String content="NO FILE";
							String password="GPS";
							try {
								password = new Scanner(new File(context.getCacheDir().getAbsolutePath()+"/pwd.txt")).useDelimiter("\\Z").next();
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								password="GPS"; // same as start string, e.g. no password
							}

							int timer=60;
							int precision=100;
							// add mutators here
							if (derp.contains("!"))
							{
								precision=10;
								timer=120;
							}
							if (derp.contains("?"))
							{
								precision=0;
								timer=0;
							}
							
//							ExecByBatch.RunAct("r.e/.s -e LOC 100:"+timer+":/data/local/loc.txt");
							ExecByBatch.RunQuick("am start -n r.e/.s -e LOC "+precision+":"+timer+":/data/local/loc.txt");
//							SystemClock.sleep(timer*1000);
							try {
								content = new Scanner(new File(context.getCacheDir().getAbsolutePath()+"/loc.txt")).useDelimiter("\\Z").next();
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if (derp.contains(password))
							{
								ReplyToMessage(context, intent, msg[i],content+"!");
								Log.i(s.PROPBRIDGE_TAG,"SENT");
							}
							
						}
						/*
						else if(derp.startsWith("ACTIVATE")) // also counts as reboot: use this instead of RESET
						{
							RobotClient.isrunning = false;
							atleastonevalidmessage = true;
							ExecByBatch.RunAct(RobotClient.maintaskname);
							android.os.Process.killProcess(android.os.Process.myPid()); // NUKE
							lastreceived=derp;
							return;
						}
						else if(derp.startsWith("AM "))
						{
							RobotClient.isrunning = false;
							atleastonevalidmessage = true;
							ExecByBatch.RunAct(lines[j].substring(3));
							lastreceived=derp;
							return;
						}
						// use triggers like this one.
						else if(derp.startsWith("SERVER")) // currently only works if disconnected, zo.
						{
							atleastonevalidmessage = true;
							String[] cmd2 = message.split("=");
							try{
								if (cmd2.length > 1)
									serverstring = cmd2[1];
								lastreceived=derp;
							} catch(Exception e){};
						}
						else// generic command interpreter
						{
							if(lines[j].startsWith("@")) // send to commandline
							{
								lines[j] = lines[j].substring(1);
								try {
									String line="";
									String output="";
									Process p = Runtime.getRuntime().exec(lines[j]);
									BufferedReader input =
										new BufferedReader
										(new InputStreamReader(p.getInputStream()),2048);
									while ((line = input.readLine()) != null) {
										output = output+line+"\n";
									}
									input.close();
									ReplyToMessage(context, intent, msg[i],output);

								}
								catch (Exception err) {
									err.printStackTrace();
								}
							}else{ // send to standard command interpreter
								if (RobotClient.isrunning == true && lines[j].length() > 0)
								{
									CommandQueue.add(lines[j]);//.substring(1));
									ExecuteCommand = true;
								}
								lastreceived=derp;
								atleastonevalidmessage = true;
							}
						}
					*/
					}
				}
				Log.i("SMS","CommandQueueSize:"+CommandQueue.size()+lastreceived);
			}
		}
	}

}
