package com.rob57530.smsserver;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.telephony.SmsMessage;
import android.util.Base64;
import android.util.Log;

public class SMSReceiver extends BroadcastReceiver
{

	class RequestTask extends AsyncTask<String, String, String>
	{
		@Override
		protected String doInBackground(String... uri)
		{
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response;
			String responseString = null;
			try
			{
				HttpGet get = new HttpGet(uri[0]);
				get.setHeader("Host", uri[1]);
				get.setHeader("Authorization", "Basic " + Base64.encodeToString("__gates__:gatespasswd".getBytes(), Base64.NO_WRAP));

				response = httpclient.execute(get);
				StatusLine statusLine = response.getStatusLine();
				if (statusLine.getStatusCode() == HttpStatus.SC_OK)
				{
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					response.getEntity().writeTo(out);
					out.close();
					responseString = out.toString();
				}
				else
				{
					response.getEntity().getContent().close();
					throw new IOException(statusLine.getReasonPhrase());
				}
			}
			catch (ClientProtocolException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			return responseString;
		}

		@Override
		protected void onPostExecute(String result)
		{
			super.onPostExecute(result);
			Log.d("SMSServerReceiver", result);
		}
	}
	
	@Override
	public void onReceive(Context context, Intent intent)
	{
		Log.d("SMSServerReceiver", "sms");
        SharedPreferences pr = PreferenceManager.getDefaultSharedPreferences(context);
        if (!pr.getBoolean("running", false))
            return;

		Log.d("SMSServerReceiver", "sms (running)");
		
		SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
		String http = p.getString("http", "");
		if(http.length() == 0)
			return;
		
		if(intent.getExtras() != null)
        {
            Object[] smsExtra = (Object[]) intent.getExtras().get("pdus");
            if(smsExtra != null)
	            for(int i=0;i<smsExtra.length;i++)
	            {
	            	try
					{
		            	SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
		            	String body = sms.getMessageBody().toString();
		            	String address = sms.getOriginatingAddress();
	            		RequestTask r = new RequestTask();
						r.execute("http://" + http + "/received.php?sender=" + URLEncoder.encode(address, "utf-8") + "&text=" + URLEncoder.encode(body, "utf-8"), http);
					}
					catch (UnsupportedEncodingException e)
					{
						e.printStackTrace();
					}
	            }
        }
	}
}
