package my.lan.zooty;

import android.app.Activity;
import android.util.Log;
import android.content.Intent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AardRemoteActivity extends Activity
{
    // Debugging
    private static final String TAG = "AardRemote";
    private static final boolean D = true;

    // Message types sent from the AardTalkerService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    // Key names received from the AardTalkerService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Name of the connected device
    private String mConnectedDeviceName = null;

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;

    EditText log_text = null;
    Button   learn_b = null;
    Button   send_b = null;
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private AardTalkerService mTalkService = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if(D) Log.d(TAG, "ON CREATE 1");
        setContentView(R.layout.main);
        if(D) Log.d(TAG, "ON CREATE 2");

        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(D) Log.d(TAG, "ON CREATE 3");

        log_text = (EditText) findViewById(R.id.log_text);

        ((Button) findViewById(R.id.connect_button)).setOnClickListener(
            new Button.OnClickListener() {
                @Override public void onClick(View v) {
                    doConnect();
                } });

        learn_b = (Button) findViewById(R.id.learn_button);
        learn_b.setOnClickListener(
            new Button.OnClickListener() {
                @Override public void onClick(View v) {
                    doLearn();
                } });

        send_b = (Button) findViewById(R.id.send_button);
        send_b.setOnClickListener(
            new Button.OnClickListener() {
                @Override public void onClick(View v) {
                    doSend();
                } });

        learn_b.setClickable(false);
        send_b.setClickable(false);
    }

    void doConnect() {
       log_text.append("doConnect called\n");
       if(D) Log.d(TAG, "doConnect 1");
       // Launch the DeviceListActivity to see devices
       Intent serverIntent = new Intent(this, DeviceListActivity.class);
       if(D) Log.d(TAG, "doConnect 2");
       startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
       if(D) Log.d(TAG, "doConnect 3");
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CONNECT_DEVICE) {
           if (resultCode == Activity.RESULT_OK) {

              // Get the device MAC address
              String address =
                 data.getExtras().getString(
                                     DeviceListActivity.EXTRA_DEVICE_ADDRESS);

              // Get the BLuetoothDevice object
              BluetoothDevice device =
                 mBluetoothAdapter.getRemoteDevice(address);

              // Attempt to connect to the device
              if (mTalkService == null) {
                 mTalkService = new AardTalkerService(this, mHandler);
              }
              mTalkService.connect(device);
           }
        }
    }

    // The Handler that gets information back from the AardTalkerService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case AardTalkerService.STATE_CONNECTED:
                    log_text.append("connected\n");
                    learn_b.setClickable(true);
                    {
                       byte[] bad = new byte[1];
                       bad[0] = 47;
                       mTalkService.write(bad);
                    }
                    break;
                case AardTalkerService.STATE_CONNECTING:
                    log_text.append("connecting...\n");
                    break;
                case AardTalkerService.STATE_NONE:
                    log_text.append("not connected\n");
                    break;
                }
                break;
            case MESSAGE_WRITE:
                {
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                StringBuilder sb = new StringBuilder();
                sb.append("->");
                for (byte b : writeBuf) {
                   sb.append(String.format(" %02X", b));
                }
                sb.append("\n");
                log_text.append(sb.toString());
                }
                break;
            case MESSAGE_READ:
                {
                byte[] readBuf = (byte[]) msg.obj;
                StringBuilder sb = new StringBuilder();
                sb.append("<-");
                for (byte b : readBuf) {
                   sb.append(String.format(" %02X", b));
                }
                sb.append("\n");
                log_text.append(sb.toString());
                }
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };

    void doLearn() {
       log_text.append("doLearn called\n");
       send_b.setClickable(true);
    }

    void doSend() {
       log_text.append("doSend called\n");
    }
}
