using ArduinoBluetoothAPI;
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

public class TestBLE : MonoBehaviour
{
    BluetoothHelper bluetoothHelper;
    BluetoothHelperCharacteristic characteristicWrite;
    BluetoothHelperService bluetoothService;
    string targetDeviceName = "Bbow_20210501";
    string deviceName = "";
    bool canConnect = true;
    [SerializeField] Text textUI;

    void OnDestroy()
    {
        if (bluetoothHelper != null)
        {
            bluetoothHelper.Disconnect();
        }
    }

    public void Connect()
    {
        if (!canConnect)
        {
            return;
        }
        canConnect = false;
        try
        {
            BluetoothHelper.BLE = true;
            bluetoothHelper = BluetoothHelper.GetNewInstance();

            bluetoothHelper.OnConnected += (BluetoothHelper helper) =>
            {
                Log("连接成功\n" + helper.getDeviceName());
                foreach (BluetoothHelperService service in helper.getGattServices())
                {
                
                    if (service.getName().ToLower().StartsWith("0000fff0"))
                    {
                        bluetoothService = service;

                        foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
                        {
                            if (characteristic.getName().ToLower().StartsWith("0000fff2"))
                            {
                                characteristicWrite = characteristic;
                            }
                            else if (characteristic.getName().ToLower().StartsWith("0000fff1"))
                            {

                                BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
                                ch.setService(bluetoothService.getName());
                                bluetoothHelper.Subscribe(ch);
                            }
                        }
                    }
                }
                StartCoroutine(SendCmdForInit());
            };
            bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
            {
                canConnect = true;
                Log("连接失败\n" + helper.getDeviceName());
            };
            bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
            {
                byte[] bytes = value;
                Log(String.Join(",", bytes));
            };
            bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
            {
                foreach (BluetoothDevice device in nearbyDevices)
                {
                    if (device.DeviceName == targetDeviceName)
                    {
                        deviceName = device.DeviceName;
                        bluetoothHelper.setDeviceName(deviceName);
                        bluetoothHelper.Connect();
                        Log("发现设备\n" + device.DeviceName);
                        return;
                    }
                }
                canConnect = true;
                Log("没有发现设备");
            };

            bluetoothHelper.ScanNearbyDevices();
            Log("正在扫描设备");
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
            canConnect = true;
            Log("请打开蓝牙");
        }
    }

    IEnumerator SendCmdForInit() {
        yield return new WaitForSecondsRealtime(2f);
        WriteData("b");
        yield return new WaitForSecondsRealtime(1f);
        WriteData("1");
        yield return new WaitForSecondsRealtime(1f);
        WriteData("3");
    }

    public void WriteData(string data)
    {
        BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
        ch.setService(bluetoothService.getName());
        bluetoothHelper.WriteCharacteristic(ch, data);
        Log("成功发送指令：" + data);
    }

    void Log(string text)
    {
        if (textUI) 
        {
            textUI.text = text;
        }
    }
}
