package com.rogerlakin.snowplowcontrol;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.Writer;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;


public class MainActivity extends AppCompatActivity {
    int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
    String TAG;
    TextView myLabel;
    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;
    OutputStream mmOutputStream;
    Writer mmWriter;
    volatile boolean stopWorker;
    char charValue;
    // UUID uuid = UUID.fromString("00001101-0000-1000-8000-D88039F0D5DD");
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00066674A57F");

    public void energyBreakPointStart(final int stateId, final String stateDescription) {
        final Intent stateUpdate = new Intent("com.quicinc.Trepn.UpdateAppState");
        stateUpdate.putExtra("com.quicinc.Trepn.UpdateAppState.Value", stateId);
        stateUpdate.putExtra("com.quicinc.Trepn.UpdateAppState.Value.Desc", stateDescription);
        sendBroadcast(stateUpdate);
    }// Generated  energyBreakPointStart method

    public void energyBreakPointEnd() {
        final Intent stateUpdate = new Intent("com.quicinc.Trepn.UpdateAppState");
        stateUpdate.putExtra("com.quicinc.Trepn.UpdateAppState.Value", 0);
        sendBroadcast(stateUpdate);
    }// Generated  energyBreakPointEnd method

    // Defines several constants used when transmitting messages between the
    // service and the UI.
    private interface MessageConstants {
        public static final int MESSAGE_READ = 0;
        public static final int MESSAGE_WRITE = 1;
        public static final int MESSAGE_TOAST = 2;

        // ... (Add other message types here as needed.)
    }

    //**********************The handler************************************
    private static final String MSG_KEY = "yo";
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            String string = bundle.getString(MSG_KEY);
            final TextView myTextView = (TextView) findViewById(R.id.label);
            myTextView.setText(string);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();

        if (actionBar != null) {
            actionBar.setDisplayShowCustomEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }

        // Getting the bluetooth adapter
      /*  mBluetoothAdapter  = BluetoothAdapter.getDefaultAdapter();
        TextView v = (TextView) getLayoutInflater().inflate(R.layout.activity_main, null);
        getSupportActionBar().setCustomView(v);*/

        Button plowDown = (Button) findViewById(R.id.plowdown);
        Button plowUp = (Button) findViewById(R.id.plowup);
        Button plowRight = (Button) findViewById(R.id.plowright);
        Button plowLeft = (Button) findViewById(R.id.plowleft);
        myLabel = (TextView) findViewById(R.id.label);

        // Use this check to determine whether BLE is supported on the device. Then
// you can selectively disable BLE-related features.
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(getApplicationContext(), "BLE_not_supported", Toast.LENGTH_LONG).show();
            finish();
        }

//************************   butons start   *********************

        plowDown.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    turnON("ON");  // 2
                    //datValue[0] = '2';
                    charValue = '2';
                    int appa = 0;
                    try {
                        sendData();
                    } catch (IOException ex) {
                    }

                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    turnON("OFF");  // C
                    charValue = 'C';
                    int appa = 0;
                    try {
                        sendData();

                    } catch (IOException ex) {
                    }
                }
                return true;
            }  // onTouch end

        }); // onButton end

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        
        //****************************   bluetooth   start  connecting   **********************//

    }  // onCreate end


    public void turnON(String Trans) {
        TextView textView = (TextView) findViewById(R.id.position);
        textView.setText(Trans);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        final int id = item.getItemId();
        switch (item.getItemId()) {
            case R.id.on:
                Toast.makeText(this, "Enable Bluetooth", Toast.LENGTH_SHORT)
                        .show();
                try {
                    findBT();
                    openBT();
                } catch (IOException ex) {
                }
                break;
            case R.id.off:
                Toast.makeText(this, "Disable Bluetooth", Toast.LENGTH_SHORT)
                        .show();
                try {
                    closeBT();
                } catch (IOException ex) {
                }

                break;

            case R.id.list_item:
                Toast.makeText(this, "List device \n" + uuid, Toast.LENGTH_LONG)
                        .show();

                break;

            default:
                break;
        }//H
        return super.onOptionsItemSelected(item);
    }


    void findBT() throws IOException {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            myLabel.setText("No bluetooth adapter available");
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                //if(device.getName().equals("RN4870-D5DD"))
                if (device.getName().equals("Unit3-A57F")) {
                    Toast.makeText(this, "Found.", Toast.LENGTH_SHORT).show();
                    mmDevice = device;
                    int dev = 0;
                    break;
                }
            }
        }
        myLabel.setText("Bluetooth Device Found");
        int dev = 1;

    }


    void openBT() throws IOException {
        Toast.makeText(this, "Openbluetooth.", Toast.LENGTH_SHORT).show();
        //UUID uuid = mmDevice.getUuids()[0].getUuid();
        // UUID uuid = UUID.fromString("00001101-0000-1000-8000-D88039F0D5DD");
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00066674A57F");
        //Unit3-A57F
        BluetoothSocket tmp = null;
        try {
            tmp = mmDevice.createRfcommSocketToServiceRecord(uuid);

            // for others devices its works with:
            // Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});

            // for galaxy tab 2 with:
            final Method m = mmDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[]{int.class});

            tmp = (BluetoothSocket) m.invoke(mmDevice, 1);
        } catch (IOException e) {

        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            Toast.makeText(this, "1", Toast.LENGTH_SHORT).show();
            ;
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            Toast.makeText(this, "2", Toast.LENGTH_SHORT).show();
            ;
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();
            ;
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            Toast.makeText(this, "4", Toast.LENGTH_SHORT).show();
            ;
        }
        mmSocket = tmp;
        Toast.makeText(this, "5", Toast.LENGTH_SHORT).show();
        ;

        mmSocket.connect();
        Log.i(TAG, "Client Connected!");

        mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(uuid);
        Toast.makeText(this, "before connect", Toast.LENGTH_SHORT).show();
        mmSocket.connect();
        Toast.makeText(this, "before stream", Toast.LENGTH_SHORT).show();
        mmOutputStream = mmSocket.getOutputStream();
        //  mmInputStream = mmSocket.getInputStream(); // not using any inputs
        Toast.makeText(this, "before listing", Toast.LENGTH_SHORT).show();
        myLabel.setText("Bluetooth Opened");
    }

    // Call this from the main activity to send data to the remote device.


    public void sendData() throws IOException {
        Toast.makeText(this, "sending:" + charValue, Toast.LENGTH_SHORT).show();
        int sso = 0;  // used for debug
        try (final OutputStreamWriter outWriter = new OutputStreamWriter(mmOutputStream)) {
            myLabel.setText("Data Sent");
            outWriter.write(charValue);
            mmOutputStream.write(charValue);
            Log.d(TAG, " at sendata()  bombs out");
        }
    }

    void closeBT() throws IOException
    {}
    
    
}  //  end of program

