using System;
using UnityEngine;

namespace SmartBowSDK
{
    public class SmartBowHelper : MonoBehaviour
    {
        private static SmartBowHelper _Instance;
        internal SmartBowNetwork smartBowNetwork;
        internal BluetoothAim_SDK bluetoothAim;
        internal AimHandler_SDK aimHandler;
        internal ShootChecker_SDK shootChecker;
        public CalibrateDataStorageMode calibrateDataStorageMode = CalibrateDataStorageMode.Remote;

        void Awake()
        {
            DontDestroyOnLoad(gameObject);
            gameObject.AddComponent<AOTAdapter_SDK>();
            smartBowNetwork = gameObject.AddComponent<SmartBowNetwork>();
            bluetoothAim = gameObject.AddComponent<BluetoothAim_SDK>();
            aimHandler = gameObject.AddComponent<AimHandler_SDK>();
            shootChecker = gameObject.AddComponent<ShootChecker_SDK>();
            smartBowNetwork.smartBowHelper = this;
            bluetoothAim.smartBowHelper = this;
            aimHandler.smartBowHelper = this;
            shootChecker.smartBowHelper = this;
        }

        /// <summary>
        /// 获取唯一实例
        /// </summary>
        /// <returns></returns>
        public static SmartBowHelper GetInstance()
        {
            if (!_Instance) _Instance = new GameObject(typeof(SmartBowHelper).Name).AddComponent<SmartBowHelper>();
            return _Instance;
        }

        /// <summary>
        /// 创建新的实例
        /// </summary>
        /// <returns></returns>
        public static SmartBowHelper NewInstance()
        {
            return new GameObject(typeof(SmartBowHelper).Name).AddComponent<SmartBowHelper>();
        }

        /// <summary>
        /// 获取一个window 蓝牙用例
        /// </summary>
        /// <returns></returns>
        public BluetoothWindows CreateBluetoothWindows()
        {

            return bluetoothAim.CreateWindowBLE();
        }

        #region 登录
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="gameID">游戏ID</param>
        /// <param name="channelID">渠道ID</param>
        /// <param name="username">账号</param>
        /// <param name="password">密码</param>
        /// <param name="callback">回调函数</param>
        public void Login(string gameID, string channelID, string username, string password, Action<LoginResult> callback)
        {
            smartBowNetwork.Login(gameID, channelID, username, password, callback);
        }

        /// <summary>
        /// 用户登出
        /// </summary>
        /// <param name="callback">回调函数</param>
        public void Logout(Action<bool> callback)
        {
            smartBowNetwork.Logout(callback);
        }

        /// <summary>
        /// 获取用户基本信息
        /// </summary>
        /// <param name="callback">回调函数</param>
        public void GetUserInfo(Action<GetUserInfoResult> callback)
        {
            smartBowNetwork.GetUserInfo(callback);
        }
        #endregion

        #region 蓝牙:蓝牙部分新增修改,添加当前判断设备mac
        ///// <summary>
        ///// 连接蓝牙模块
        ///// </summary>
        //public void Connect()
        //{
        //    //之前的默认不用判断mac
        //    //当前连接不需要需要检测设备，设置为null
        //    bluetoothAim.ResetAimDeviceInfoToNull();

        //    bluetoothAim.Connect();
        //}

        /// <summary>
        /// 连接蓝牙模块
        /// 新增连接操作，需要用户标签和设备id
        /// userTags: 存储的信息标签，按实际用户区分
        /// deviceId：对应设备id，同一个用户下的不同设备
        /// bRecreateDeviceInfo: 重新创建设备信息。false 的情况下默认限制mac
        /// </summary>
        public void Connect(string userTags,int deviceId, bool bRecreateDeviceInfo = false)
        {
            if (userTags == null || userTags.Length == 0)
            {
                SmartBowLogger.LogError(this, $"清除信息错误，userTags不能为空！");
                return;
            }
            if (deviceId <= 0)
            {
                SmartBowLogger.LogError(this, $"清除信息错误，deviceId 不能小于等于 0！");
                return;
            }
            //判断mac需要创建一个连接信息
            bluetoothAim.initAimDeviceInfo(userTags,deviceId,bRecreateDeviceInfo);
            //进行蓝牙连接
            bluetoothAim.Connect();
        }
        /// <summary>
        /// 清空建立的蓝牙判断数据
        /// userTags: 存储的信息标签，按实际用户区分
        /// deviceId：对应设备id，同一个用户下的不同设备
        /// </summary>
        public void ClearDeviceInfo(string userTags,int deviceId)
        {
            if (userTags == null || userTags.Length == 0)
            {
                SmartBowLogger.LogError(this, $"清除信息错误，userTags不能为空！");
                return;
            }
            if (deviceId <= 0)
            {
                SmartBowLogger.LogError(this, $"清除信息错误，deviceId 不能小于等于 0！");
                return ;
            }
            bluetoothAim.onClearAimDeviceInfoByDeviceId(userTags, deviceId);
        }
        /// <summary>
        /// 获取存储的数据
        /// userTags: 存储的信息标签，按实际用户区分
        /// deviceId：对应设备id，同一个用户下的不同设备
        /// </summary>
        public AimDeviceInfo GetDeviceInfo(string userTags, int deviceId) {
            if (userTags == null || userTags.Length == 0)
            {
                SmartBowLogger.LogError(this, $"清除信息错误，userTags不能为空！");
                return null;
            }
            if (deviceId <= 0)
            {
                SmartBowLogger.LogError(this, $"清除信息错误，deviceId 不能小于等于 0！");
                return null;
            }
            return bluetoothAim.onGetAimDeviceInfos(userTags, deviceId);
        }

        /// <summary>
        /// 断开蓝牙模块
        /// </summary>
        public void Disconnect()
        {
            bluetoothAim.Disconnect();
        }

        /// <summary>
        /// 获取蓝牙状态
        /// </summary>
        /// <returns>蓝牙状态</returns>
        public BluetoothStatusEnum GetBluetoothStatus()
        {
            return bluetoothAim.bluetoothStatus;
        }

        /// <summary>
        /// 监听蓝牙状态变化
        /// </summary>
        public event BluetoothStatusChangedEvent OnBluetoothStatusChanged;

        /// <summary>
        /// 判断蓝牙模块是否初始化完成
        /// </summary>
        /// <returns>蓝牙模块是否初始化完成</returns>
        public bool IsBluetoothModuleInited()
        {
            return bluetoothAim.moduleInited;
        }

        /// <summary>
        /// 监听蓝牙模块初始化完成
        /// Tip:连接蓝牙模块成功后会有几秒的初始化过程，初始化完成后才能进行传感器相关的函数调用。
        /// </summary>
        public Action OnBluetoothModuleInited;

        /// <summary>
        /// 监听蓝牙错误
        /// </summary>
        public event BluetoothErrorEvent OnBluetoothError;

        /// <summary>
        /// 获取Mac地址
        /// Tip:需要模块初始化完成才能获取
        /// </summary>
        /// <returns>如果返回null则是获取失败</returns>
        public string GetMacAddress()
        {
            return bluetoothAim.macAddress;
        }

        /// <summary>
        /// 获取电量
        /// Tip:需要模块初始化完成才能获取
        /// </summary>
        /// <returns>电量值（范围0~100），值为0时也代表获取失败</returns>
        public int GetBattery()
        {
            return bluetoothAim.battery;
        }

        /// <summary>
        /// 设置目标设备名称（用于搜索和连接）
        /// </summary>
        /// <param name="deviceName">设备名称</param>
        public void SetTargetDeviceName(string deviceName)
        {
            bluetoothAim.deviceConfig.deviceName = deviceName;
        }
        #endregion

        #region 传感器
        /// <summary>
        /// 开启九轴传感
        /// </summary>
        /// <returns>请求是否发送成功</returns>
        public bool StartRotationSensor()
        {
            return bluetoothAim.RequestOpen9Axis();
        }

        /// <summary>
        /// 停止九轴传感
        /// </summary>
        /// <returns>请求是否发送成功</returns>
        public bool StopRotationSensor()
        {
            return bluetoothAim.RequestClose9Axis();
        }

        /// <summary>
        /// 监听姿态角更新
        /// </summary>
        public event RotationUpdateEvent OnRotationUpdate;

        /// <summary>
        /// 开启射箭传感
        /// </summary>
        /// <returns>请求是否发送成功</returns>
        public bool StartShootingSensor()
        {
            return bluetoothAim.RequestOpenInfrared();
        }

        /// <summary>
        /// 停止射箭传感
        /// </summary>
        /// <returns>请求是否发送成功</returns>
        public bool StopShootingSensor()
        {
            return bluetoothAim.RequestCloseInfrared();
        }

        /// <summary>
        /// 监听射箭
        /// </summary>
        public ShootingEvent OnShooting;

        /// <summary>
        /// 开始陀螺仪校准
        /// </summary>
        public void StartGyrCalibration()
        {
            aimHandler.StartGyrCalibration();
        }

        /// <summary>
        /// 停止陀螺仪校准
        /// </summary>
        public void StopGyrCalibration()
        {
            aimHandler.StopGyrCalibration();
        }

        /// <summary>
        /// 判断陀螺仪是否正在校准
        /// </summary>
        /// <returns>陀螺仪是否正在校准</returns>
        public bool IsGyrCalibrating()
        {
            return aimHandler.IsGyrCalibrating();
        }

        /// <summary>
        /// 获取陀螺仪校准进度
        /// </summary>
        /// <returns>陀螺仪校准进度</returns>
        public float GetGyrProgress()
        {
            return aimHandler.GetGyrProgress();
        }

        /// <summary>
        /// 判断陀螺仪是否校准完成
        /// </summary>
        /// <returns>陀螺仪是否校准完成</returns>
        public bool IsGyrCompleted()
        {
            return aimHandler.IsGyrCompleted();
        }

        /// <summary>
        /// 开始地磁计校准
        /// </summary>
        public void StartMagCalibration()
        {
            aimHandler.StartMagCalibration();
        }

        /// <summary>
        /// 判断地磁计是否校准完成
        /// </summary>
        /// <returns>地磁计是否校准完成</returns>
        public bool IsMagCompleted()
        {
            return aimHandler.IsMagCompleted();
        }

        /// <summary>
        /// 视角归位
        /// </summary>
        public void ResetAim()
        {
            aimHandler.DoIdentity();
        }

        /// <summary>
        /// 监听模块的功能键短按
        /// </summary>
        public Action OnFunctionKeyPress;

        /// <summary>
        /// 监听模块的功能键长按
        /// </summary>
        public Action OnFunctionKeyLongPress;
        #endregion

        /// <summary>
        /// 蓝牙状态变化事件
        /// </summary>
        /// <param name="oldStatus">旧状态</param>
        /// <param name="newStatus">新状态</param>
        public delegate void BluetoothStatusChangedEvent(BluetoothStatusEnum oldStatus, BluetoothStatusEnum newStatus);
        internal void InvokeOnBluetoothStatusChanged(BluetoothStatusEnum oldStatus, BluetoothStatusEnum newStatus)
        {
            try
            {
                OnBluetoothStatusChanged?.Invoke(oldStatus, newStatus);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        /// <summary>
        /// 蓝牙错误事件
        /// </summary>
        /// <param name="error">错误类型</param>
        /// <param name="message">消息描述</param>
        public delegate void BluetoothErrorEvent(BluetoothError error, string message);
        internal void InvokeOnBluetoothError(BluetoothError error, string message)
        {
            try
            {
                OnBluetoothError?.Invoke(error, message);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        internal void InvokeOnFunctionKeyPress()
        {
            try
            {
                OnFunctionKeyPress?.Invoke();
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        internal void InvokeOnFunctionKeyLongPress()
        {
            try
            {
                OnFunctionKeyLongPress?.Invoke();
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        /// <summary>
        /// 姿态角更新事件
        /// </summary>
        /// <param name="rotation">姿态角</param>
        public delegate void RotationUpdateEvent(Quaternion rotation);
        internal void InvokeOnRotationUpdate(Quaternion rotation)
        {
            if (bluetoothAim.bluetoothStatus != BluetoothStatusEnum.Connected) return;
            try
            {
                OnRotationUpdate?.Invoke(rotation);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        /// <summary>
        /// 射箭事件
        /// </summary>
        /// <param name="speed">速度（m/s）</param>
        public delegate void ShootingEvent(float speed);
        internal void InvokeOnShooting(float speed)
        {
            try
            {
                OnShooting?.Invoke(speed);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        internal void InvokeOnBluetoothModuleInited()
        {
            try
            {
                OnBluetoothModuleInited?.Invoke();
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }

        /// <summary>
        /// 监听枪状态
        /// </summary>
        public BleDeviceEvent OnBleDeviceState;

        /// <summary>
        /// 硬件对应的事件
        /// </summary>
        public delegate void BleDeviceEvent(BluetoothDeviceType bleDeviceType, BluetoothDeviceStatus gunStatusEnum);
        internal void InvokeOnBleDevice(BluetoothDeviceType bleDeviceType, BluetoothDeviceStatus gunStatusEnum)
        {
            try
            {
                OnBleDeviceState?.Invoke(bleDeviceType,gunStatusEnum);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
    }
}
