package com.example.interruptor;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.UiAutomation;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.SoundPool;
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;

import androidx.core.app.ActivityCompat;

public class MainActivity extends Activity implements OnClickListener {

    private ImageView im;
    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 estado,tipoBoton;
    private int ENCENDIDO=R.drawable.on1,APAGADO=R.drawable.off1;
    public SoundPool sp;
    public int flujodemusica;
    // 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 = "20:15:05:06:76:02";


    // 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);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        estado = false;
        tipoBoton = false;
        btn1 = findViewById(R.id.button);
        btn1.setOnClickListener(this);
        im = findViewById(R.id.imageView);
        im.setOnClickListener(this);
        im.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                tipoBoton=!tipoBoton;
                if (!tipoBoton){
                    ENCENDIDO=R.drawable.on1;
                    APAGADO=R.drawable.off1;
                }else{
                    ENCENDIDO=R.drawable.encendido;
                    APAGADO=R.drawable.apagado;
                }
                return true;
            }
        });
        sp = new SoundPool(8,AudioManager.STREAM_MUSIC, 0);
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        flujodemusica=sp.load(this, R.raw.clic, 1);
// 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 (Exception 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(address))
                msg = msg + ".\n\nModifique la dirección del servidor a "+address+" 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);
                    try{
                        Thread.sleep(300);
                    }catch (Exception e){}
                    sp.play(flujodemusica, 1, 1, 0, 0, 1);
                    sendDataWithoutResponse(97);
                    try{
                        Thread.sleep(100);
                    }catch (Exception e){}
                }

                finish();
                break;
            case R.id.imageView :
                if (!estado) {
                    sendDataWithoutResponse(65);
                    im.setImageResource(ENCENDIDO);
                    estado=true;
                }else{
                    sendDataWithoutResponse(97);
                    im.setImageResource(APAGADO);
                    estado=false;
                }
                sp.play(flujodemusica, 1, 1, 0, 0, 1);
                break;


        }
    }
}

