package com.rob57530.smsserver;

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.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.util.Base64;

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 java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ADBReceiver extends BroadcastReceiver {

    private String m_http;

    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 ADBReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
        if (!p.getBoolean("running", false))
            return;

        m_http = p.getString("http", "");
        String number = intent.getStringExtra("number");
        String text = intent.getStringExtra("text");
        final int id = intent.getIntExtra("id", -1);
        if (id == -1)
            return;
        else if (number == null || number.length() == 0
                || text == null || text.length() == 0)
            new RequestTask().execute("http://" + m_http + "/sent.php?id=" + id + "&status=7");
        else
        {
            try
            {
                String SENT = "SMS_SENT";
                PendingIntent sent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, new Intent(SENT), 0);
                context.getApplicationContext().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;

                        new RequestTask().execute("http://" + m_http + "/sent.php?id="
                                + id + "&status=" + r);
                    }
                }, new IntentFilter(SENT));

                SmsManager.getDefault().sendTextMessage(number, null, text, sent, null);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
