package com.example.ejemplobluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {

    private ImageView btnA, btnR, btnV;
    private Button btn1;
    private static final int REQUEST_ENABLE_BT = 1;
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private OutputStream outStream = null;
    private InputStream inStream = null;
    private boolean amarillo,rojo,verde;
    // Identificador único universal para el dispositivo bluetooth donde corre esta aplicación
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    // Dirección MAC del dispositivo remoto
    private static String address = "C8:F0:9E:4E:A2:8E";
    // Se invoca este método al crear la actividad, creando la vista así como la creación y verificación
// de estado del adaptador bluetooth
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        amarillo=rojo=verde=false;
        btn1=(Button)findViewById(R.id.button);
        btn1.setOnClickListener(this);
        btnA = (ImageView) findViewById(R.id.imageView);
        //btnA.setScaleX(2);
        //btnA.setScaleY(2);
        btnR = (ImageView) findViewById(R.id.imageView2);
        //btnR.setScaleX(2);
        //btnR.setScaleY(2);
        btnV = (ImageView) findViewById(R.id.imageView3);
        //btnV.setScaleX(2);
        //btnV.setScaleY(2);
        btnA.setOnClickListener(this);
        btnR.setOnClickListener(this);
        btnV.setOnClickListener(this);
// Se obtiene adaptador BT
        btAdapter = BluetoothAdapter.getDefaultAdapter();
// Verifica estado del adaptador BT
        checkBTState();
    }
    // Se invoca este método cuando la aplicación está a punto de hacerse visible para el usuario
    @SuppressLint("MissingPermission")
    @Override
    public void onResume() {
        super.onResume();
// Se obtiene dispositivo Bluetooth
        BluetoothDevice device = btAdapter.getRemoteDevice(address);
        try {
// Se obtiene socket
            btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            errorExit("Error fatal", "En onResume() falla al crear socket: " + e.getMessage() + ".");
        }
// Se cancela la función de descubrimiento
        btAdapter.cancelDiscovery();
        try {
// Se establece conexión con el socket
            btSocket.connect();
        } catch (IOException e) {
            try {
// Si hay problemas el conectar al socket éste se cierra
                btSocket.close();
            } catch (IOException e2) {
                errorExit("Erro fatal", "En onResume() falla al cerrar el socket al fallar intento de conexión" + e2.getMessage() + ".");
            }
        }
        try {
// Se abren flujos de entrada y salida a través de la conexión establecida
            outStream = btSocket.getOutputStream();
            inStream = btSocket.getInputStream();
        } catch (IOException e) {
            errorExit("Error fatal", "En onResume() falla la crear flujos de salida y/o entrada" + e.getMessage() + ".");
        }
    }
    @Override
    public void onPause() {
        super.onPause();
        if (outStream != null) {
            try {
// Se limpian los flujos
                outStream.flush();
            } catch (IOException e) {
                errorExit("Error fatal", "En onPause() falla al liberar el flujo de salida" + e.getMessage() + ".");
            }
        }
        try {
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Error fatal", "En onPause() falla al cerrar el socket." + e2.getMessage() + ".");
        }
    }
    @SuppressLint("MissingPermission")
    private void checkBTState() {
        if(btAdapter==null) {
            errorExit("Error fatal", "Bluetooth no soportado");
        } else {
            if (!btAdapter.isEnabled()) {
// Si el adaptador no está habilitado se habilita
                Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            } else {
// Estado habilitado
            }
        }
    }
    private void errorExit(String title, String message){
        Toast msg = Toast.makeText(getBaseContext(),
                title + " - " + message, Toast.LENGTH_SHORT);
        msg.show();
        finish();
    }
    // Envia un dato al dispositivo remoto sin recibir respuesta.
    private void sendDataWithoutResponse(int m) {
        try {
            outStream.write(m);
        } catch (IOException e) {
            String msg = "En onResume() excepción ocurrida al escribir en el flujo: " + e.getMessage();
            if (address.equals("C8:F0:9E:4E:A2:8E"))
                msg = msg + ".\n\nModifique la dirección del servidor a C8:F0:9E:4E:A2:8E como dirección correcta";
            msg = msg + ".\n\nChequear que el SPP UUID: " + MY_UUID.toString() + " exista.\n\n";
            errorExit("Error fatal", msg);
        }
    }
    // Envía un dato m recibiendo respuesta del dispositivo remoto recibiendo caracteres hasta encontrar una arroba como
// caracter de terminación. El caracter de terminación depende del que se programe en el dispositivo remoto.
    private void sendData(int m) {
        try {
            outStream.write(m);
            try{Thread.sleep(250);} catch(Exception e){}
            int dato=inStream.read();
            while (dato!=64){
                    dato=inStream.read();
            }
        } catch (IOException e) {
            String msg = "En onResume() excepción ocurrida al escribir en el flujo: " + e.getMessage();
            if (address.equals("C8:F0:9E:4E:A2:8E"))
                msg = msg + ".\n\nModifique la dirección del servidor a C8:F0:9E:4E:A2:8E2 como dirección correcta";
            msg = msg + ".\n\nChequear que el SPP UUID: " + MY_UUID.toString() + " exista.\n\n";
            errorExit("Error fatal", msg);
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button:
                for(int i=1;i<=10;i++)
                {
                    sendDataWithoutResponse(65);
                    sendDataWithoutResponse(82);
                    sendDataWithoutResponse(86);
                    try{
                        Thread.sleep(300);
                    }catch (Exception e){}
                    sendDataWithoutResponse(97);
                    try{
                        Thread.sleep(100);
                    }catch (Exception e){}
                }
                finish();
                break;
            case R.id.imageView :
                if (!amarillo) {
                    sendDataWithoutResponse(65);
                    btnA.setImageResource(R.drawable.encendido);
                    btnR.setImageResource(R.drawable.apagado);
                    btnV.setImageResource(R.drawable.apagado);
                    amarillo=true;
                    rojo=verde=false;
                }else{
                    sendDataWithoutResponse(97);
                    btnA.setImageResource(R.drawable.apagado);
                    amarillo=false;
                }
                break;
            case R.id.imageView3 :
                if (!verde) {
                    sendDataWithoutResponse(86);
                    btnV.setImageResource(R.drawable.encendido);
                    btnA.setImageResource(R.drawable.apagado);
                    btnR.setImageResource(R.drawable.apagado);
                    verde=true;
                    amarillo=rojo=false;
                }else{
                    sendDataWithoutResponse(97);
                    btnV.setImageResource(R.drawable.apagado);
                    verde=false;
                }
                break;
            case R.id.imageView2 :
                if (!rojo) {
                    sendDataWithoutResponse(82);
                    btnR.setImageResource(R.drawable.encendido);
                    btnA.setImageResource(R.drawable.apagado);
                    btnV.setImageResource(R.drawable.apagado);
                    rojo=true;
                    amarillo=verde=false;
                }else{
                    sendDataWithoutResponse(97);
                    btnR.setImageResource(R.drawable.apagado);
                    rojo=false;
                }
                break;
        }
    }
}