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

namespace DuckHunter
{
    public class ConnectAdvertising : MonoBehaviour
    {

        Button advertisingBtn;

        Text advertisingText;

        GameObject connectTip;

        float speed = 10.0f;
        Vector3 targetPos = Vector3.zero;

        private BluetoothHelper helper;
        private BluetoothHelperCharacteristic characteristicWrite;
        private BluetoothHelperService bluetoothService;

        private bool isScanning;
        private bool isConnecting;

        private string data;
        private string tempVector;
        private string tmp;
        private string targetDeviceName = "SLAM_Advertiser";
        private string deviceName = "";
        string targetDeviceService = "0000fff1";
        string targetDeviceCharacteristicWrite = "0000ff11";
        string targetDeviceCharacteristicNotify = "0000ff11";

        private LinkedList<BluetoothDevice> devices;


        public GUIBox gUIBox;

        void Awake()
        {

            GameObject AdVertiserManagerObj = GameObject.Find("AdVertiserManager");
            if (AdVertiserManagerObj)
            {
                //刷新一次持久化对象的状态
                AdVertiserManagerObj.GetComponent<ConnectAdvertising>().OnUpdateState();
                Destroy(gameObject);
                return;
            }
            DontDestroyOnLoad(gameObject);
            transform.name = "AdVertiserManager";
            OnUpdateState();

        }
        public void OnUpdateState()
        {
            advertisingBtn = GameObject.Find("GameManager/GameUI/ConnectButton").GetComponent<Button>();
            advertisingText = advertisingBtn.transform.Find("Text").GetComponent<Text>();
            connectTip = GameObject.Find("GameManager/GameUI/ConnectTip");
            connectTip.SetActive(true);
            if (helper == null)
                return;
            if (!helper.isConnected() && !isScanning && !isConnecting)
            {
                //未连接，未扫描，不是连接中
                advertisingText.text = "点击连接";

            }
            else if (!helper.isConnected() && isScanning)
            {
                //扫描中
                advertisingText.text = "扫描中...";
            }
            else if (helper.isConnected())
            {
                //已连接
                advertisingText.text = "已连接";
                connectTip.SetActive(false);
            }
        }
        // Start is called before the first frame update
        void Start()
        {

            if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
            {
                Debug.Log("蓝牙未打开！");
                return;
            }

            tempVector = "";
            data = "";
            tmp = "";
            try
            {


                BluetoothHelper.BLE = true;
                helper = BluetoothHelper.GetInstance();
                helper.OnConnected += OnConnected;
                helper.OnConnectionFailed += OnConnectionFailed;
                helper.OnScanEnded += OnScanEnded;
                helper.OnCharacteristicChanged += (helper, value, characteristic) =>
                {
                    byte[] bytes = value;

                    if (bytes.Length > 1)
                    {
                        // StringBuilder builder = new StringBuilder();
                        // builder.Append(string.Format("{0:X2}", bytes[0]));
                        string flag = getBytesToIndex(bytes, 0);
                        //Debug.Log("flag:" + ToHexStrFromByte(value));
                        if (flag.ToLower() == "ff")
                        {
                            float endXFloat = onVectorValue(bytes, 2);
                            float endYFloat = onVectorValue(bytes, 5);
                            //Debug.Log("endFloat:(" + endXFloat.ToString("F4") + "," + endYFloat.ToString("F4") + ")");
                            //data += "\n<" + " 输出:("+ endXFloat.ToString("F4")+","+ endYFloat.ToString("F4")+")";
                            //tempVector = "(" + endXFloat.ToString("F4") + "," + endYFloat.ToString("F4") + ")";

                            //更新对应的屏幕坐标
                            //if (endXFloat >= 0 && endYFloat >= 0)

                            CrossHair.Instance.transform.position = new Vector3(endXFloat * Screen.width, endYFloat * Screen.height, 0);

                        }
                        else if (flag.ToLower() == "aa")
                        {
                            //模拟射击
                            float endXFloat = onVectorValue(bytes, 2);
                            float endYFloat = onVectorValue(bytes, 5);
                            Debug.Log("aa endFloat:(" + endXFloat.ToString("F4") + "," + endYFloat.ToString("F4") + ")");
                            CrossHair.Instance.transform.position = new Vector3(endXFloat * Screen.width, endYFloat * Screen.height, 0);
                            GameManager.Instance.OnModuleShooting(10);

                        }
                        else if (flag.ToLower() == "bb")
                        {
                            //切换游戏光标
                            string _crosshair = getBytesToIndex(bytes, 1);
                            // Debug.Log("_crosshair:" + _crosshair);
                            // Debug.Log("_crosshair.ToLower():" + _crosshair.ToLower());
                            if (_crosshair.ToLower() == "00")
                            {
                                //显示游戏光标
                                gUIBox.onSetCrossHairImage(true);
                                PlayerPrefs.SetInt("CrossHairImageActive", 1);
                            }
                            else if (_crosshair.ToLower() == "01")
                            {
                                //隐藏游戏光标
                                gUIBox.onSetCrossHairImage(false);
                                PlayerPrefs.SetInt("CrossHairImageActive", 0);
                            }

                        }

                    }
                    else
                    {
                        //Debug.Log(String.Join(",", bytes));
                        Debug.Log(characteristic.getName() + " 输出: " + ToHexStrFromByte(value));
                        //System.Text.Encoding.ASCII.GetString(value)
                        data += "\n<" + characteristic.getName() + " 输出: " + ToHexStrFromByte(value);

                    }

                };

                connectTip.SetActive(false);
                // if (BluetoothHelperAndroid.RequestBluetoothPermissions(() =>
                //     {
                //         isScanning = helper.ScanNearbyDevices();
                //     }, (permission) =>
                //     {
                //         if (permission.Contains("LOCATION"))
                //         {
                //             Debug.Log("exception2");
                //         }
                //         else if (permission.Contains("BLUETOOTH"))
                //         {
                //             Debug.Log("exception3");
                //         }
                //     })) return;
                // isScanning = helper.ScanNearbyDevices();

            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }



        }
        string getBytesToIndex(byte[] bytes, int index)
        {
            StringBuilder builderCrosshair = new StringBuilder();
            builderCrosshair.Append(string.Format("{0:X2}", bytes[index]));
            return builderCrosshair.ToString().Trim();
        }
        float onVectorValue(byte[] bytes, int startIndex)
        {
            //整数部分
            string intPartHex = string.Format("{0:X2}", bytes[startIndex]).ToString().Trim(); ;
            int intPartNumber = Convert.ToInt32(intPartHex, 16);
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < 2; i++)
            {
                builder.Append(string.Format("{0:X2}", bytes[i + startIndex + 1]));
            }
            string dataHex = builder.ToString().Trim();
            int decimalPartNumber = Convert.ToInt32(dataHex, 16);
            return intPartNumber + (float)decimalPartNumber / 32768;
        }

        void OnScanEnded(BluetoothHelper helper, LinkedList<BluetoothDevice> devices)
        {

            if (devices.Count == 0)
            {
                isScanning = helper.ScanNearbyDevices();
                Debug.Log("OnScanEnded:" + devices.Count);
                return;
            }
            this.isScanning = false;
            foreach (BluetoothDevice device in devices)
            {
                if (device.DeviceName == targetDeviceName)
                {
                    deviceName = device.DeviceName;
                    helper.setDeviceName(deviceName);
                    try
                    {
                        helper.Connect();
                        isConnecting = true;
                    }
                    catch (Exception)
                    {
                        isConnecting = false;
                    }
                    Debug.Log("匹配设备 " + device.DeviceName);
                    return;
                }
            }
        }

        void OnConnected(BluetoothHelper helper)
        {
            isConnecting = false;
            connectTip.SetActive(false);
            Debug.Log("连接成功:" + helper.getDeviceName());
            foreach (BluetoothHelperService service in helper.getGattServices())
            {
                if (service.getName().ToLower().StartsWith(targetDeviceService))
                {
                    bluetoothService = service;
                    foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
                    {
                        if (characteristic.getName().ToLower().StartsWith(targetDeviceCharacteristicWrite))
                        {
                            characteristicWrite = characteristic;
                            BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
                            ch.setService(bluetoothService.getName());
                            helper.Subscribe(ch);
                        }
                    }
                    Debug.Log("Connected");
                }
            }
        }

        void OnConnectionFailed(BluetoothHelper helper)
        {
            isConnecting = false;
            Debug.Log("Connection lost");
            advertisingText.text = "点击连接";
        }

        void Update()
        {


            if (helper == null)
                return;
            // if (targetPos != CrossHair.Instance.transform.position)
            // {
            //     Vector3 lerp = Vector3.Lerp(CrossHair.Instance.transform.position, targetPos, Time.deltaTime * speed);
            //     CrossHair.Instance.transform.position = lerp;
            // }
            if (!helper.isConnected() && !isScanning && !isConnecting)
            {
                //未连接，未扫描，不是连接中
                advertisingText.text = "点击连接";

            }
            else if (!helper.isConnected() && isScanning)
            {
                //扫描中
                advertisingText.text = "扫描中...";
            }
            else if (helper.isConnected())
            {
                //已连接
                advertisingText.text = "已连接";
            }
        }

        public void OnAdvertisingClick()
        {
            // float _randomX = (float)new System.Random().Next(0, 100) / 100;
            //  float _randomY = (float)new System.Random().Next(0, 100) / 100;
            // Debug.Log("_random:"+_randomX + "," + _randomY);
            // CrossHair.Instance.transform.position = new Vector3(_randomX * Screen.width, _randomY* Screen.height, 0);

            if (helper == null)
                return;
            if (!helper.isConnected() && !isScanning && !isConnecting)
            {
                //未连接，未扫描，不是连接中
                if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
                {
                    Debug.Log("exception1");
                    return;
                }

                if (BluetoothHelperAndroid.RequestBluetoothPermissions(() =>
                 {
                     isScanning = helper.ScanNearbyDevices();
                 }, (permission) =>
                 {
                     if (permission.Contains("LOCATION"))
                     {
                         Debug.Log("exception2");
                     }
                     else if (permission.Contains("BLUETOOTH"))
                     {
                         Debug.Log("exception3");
                     }
                 })) return;
                isScanning = helper.ScanNearbyDevices();
            }
            else if (!helper.isConnected() && isScanning)
            {
                //扫描中
                advertisingText.text = "扫描中...";
            }
            else if (helper.isConnected())
            {
                //已连接，断开连接
                helper.Disconnect();
            }
        }





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

        /// <summary>
        /// 字节数组转16进制字符串：空格分隔
        /// </summary>
        /// <param name="byteDatas"></param>
        /// <returns></returns>
        public string ToHexStrFromByte(byte[] byteDatas)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < byteDatas.Length; i++)
            {
                builder.Append(string.Format("{0:X2} ", byteDatas[i]));
            }
            return builder.ToString().Trim();
        }

    }
}