package com.rob57530.smsserver;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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 org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.telephony.SmsManager;
import android.util.Base64;
import android.util.Log;

public class HttpHandler extends AbstractHandler
{
	private String m_http = null;
	private Context m_context = null;
	private Vector<Integer> m_ids = new Vector<Integer>();

	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", m_http);
				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);
		}
	}

	public void setContext(Context c)
	{
		m_context = c;
	}

	public void setHttp(String h)
	{
		m_http = h;
	}

	@Override
	public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		response.setContentType("application/json;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
		JSONObject root = new JSONObject();
		if (target.equals("/send.php"))
		{
			String number = request.getParameter("to");
			String text = request.getParameter("text");
			int idTmp = -1;
			try
			{
				idTmp = Integer.parseInt(request.getParameter("id"));
			} 
			catch(Exception e)
			{
				idTmp = m_ids.size();
				m_ids.add(0);
			}
			final int id = idTmp;
			if (number == null || number.length() == 0)
			{
				try
				{
					root.put("error", "Empty recipient");
				}
				catch (JSONException e)
				{
					response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				}
			}
			else if (text == null || text.length() == 0)
			{
				try
				{
					root.put("error", "Empty text");
				}
				catch (JSONException e)
				{
					response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				}
			}
			else
			{
				try
				{
					PendingIntent sent = null;
					if (m_http.length() != 0 && id != -1)
					{
						String SENT = "SMS_SENT";
						sent = PendingIntent.getBroadcast(m_context, 0, new Intent(SENT), 0);
						m_context.registerReceiver(new BroadcastReceiver()
						{
							@Override
							public void onReceive(Context arg0, Intent arg1)
							{
								int r = getResultCode();
								if (r == Activity.RESULT_OK)
									r = 1;
								else if (r == SmsManager.RESULT_ERROR_GENERIC_FAILURE)
									r = 3;
								else if (r == SmsManager.RESULT_ERROR_NO_SERVICE)
									r = 4;
								else if (r == SmsManager.RESULT_ERROR_NULL_PDU)
									r = 5;
								else if (r == SmsManager.RESULT_ERROR_RADIO_OFF)
									r = 6;
								else
									r = 7;
								
								RequestTask re = new RequestTask();
								re.execute("http://" + m_http + "/sent.php?id=" + id + "&status=" + r);
							}
						}, new IntentFilter(SENT));
					}

					Log.d("SMSServerService", number);
					SmsManager.getDefault().sendTextMessage(number, null, text, sent, null);
					root.put("id", 0);
					root.put("status", 0);
				}
				catch (Exception e)
				{
					e.printStackTrace();
					try
					{
						root.put("error", e.getMessage());
					}
					catch (JSONException e1)
					{
						e1.printStackTrace();
					}
				}
			}
		}
		else
			return;
		baseRequest.setHandled(true);
		response.getWriter().println(root.toString());
	}
}
