using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using SLAMUVC;
using UnityEngine.UI;
using SmartBowSDK;

namespace InfraredManager
{
    public class InfraredCameraHelper
    {
        #region 单例
        private static InfraredCameraHelper _Instance;
        public static InfraredCameraHelper GetInstance()
        {
            if (_Instance == null) _Instance = new();
            return _Instance;
        }
        #endregion

        #region 创建销毁
        private GameObject _managerObject;
        private ScreenLocate _screenLocate;
        private UVCManager _uvcManager;

        public static List<RawImage> InfraredCameraHelperRawImageList = new();
        public void Create(int defWidth = 320, int defHeight = 240)
        {
            if (_managerObject) return;
            string prefabName = "WebCameraView";
            var o = UnityEngine.Object.Instantiate(Resources.Load<GameObject>(prefabName));

            UnityEngine.Object.DontDestroyOnLoad(o);
            o.name = prefabName;
            _screenLocate = o.GetComponent<ScreenLocate>();
            _screenLocate.InfraredCameraHelper = this;
            _uvcManager = o.GetComponent<UVCManager>();
            _uvcManager.startUVCManager.AddListener(_screenLocate.UVCIsReady);
            _uvcManager.updateUVCManager.AddListener(_screenLocate.UVCUpdate);
            _uvcManager.DefaultWidth = defWidth;
            _uvcManager.DefaultHeight = defHeight;
            Debug.Log("InitUVCManagerCamera 初始化相机，size：[" + _uvcManager.DefaultWidth + "," + _uvcManager.DefaultHeight + "]");
            _managerObject = o;
            if (Application.platform == RuntimePlatform.Android) Application.targetFrameRate = 60;
        }

        /// <summary>
        /// 在pc里面创建此预制
        /// </summary>
        public void CreateToPc()
        {
            if (_managerObject) return;
            string prefabName = "WebCameraView_Pc";
            var o = UnityEngine.Object.Instantiate(Resources.Load<GameObject>(prefabName));
            UnityEngine.Object.DontDestroyOnLoad(o);
            o.name = "WebCameraView";
            _screenLocate = o.GetComponent<ScreenLocate>();
            _screenLocate.InfraredCameraHelper = this;
            _uvcManager = o.GetComponent<UVCManager>();
            _managerObject = o;
        }

        public void Dispose()
        {
            if (_managerObject) UnityEngine.Object.DestroyImmediate(_managerObject);
            if (_Instance == this) _Instance = null;
        }
        #endregion

        #region 画面接口
        public void onStartPreview()
        {
            _uvcManager.onStartPreview();
        }
        public void onStopPreview()
        {
            _uvcManager.onStopPreview();
        }
        /// <summary>
        /// 获取摄像机对象CameraInfo
        /// </summary>
        public UVCManager.CameraInfo GetUVCCameraInfo()
        {
            return _screenLocate.mUVCCameraInfo;
        }
        /// <summary>
        /// 获取相机画面贴图
        /// </summary>
        public Texture GetCameraTexture()
        {
            return _screenLocate.getUVCTexture; //_screenLocate.rawImage.texture;
        }
        /// <summary>
        /// 获取相机画面材质
        /// </summary>
        public Material GetCameraMaterial()
        {
            return null;//_screenLocate.rawImage.material;
        }
        /// <summary>
        /// 设置亮度（-1~1）
        /// </summary>
        public void SetBrightness(float value)
        {
            //_screenLocate.rawImage.material.SetFloat("_Brightness", value);
            _screenLocate.pcBrightness = value;
        }
        /// <summary>
        /// 获取亮度（-1~1）
        /// </summary>
        public float GetBrightness()
        {
            return _screenLocate.pcBrightness;// _screenLocate.rawImage.material.GetFloat("_Brightness");
        }
        /// <summary>
        /// 设置对比度（-1~1）
        /// </summary>
        public void SetContrast(float value)
        {
            // _screenLocate.rawImage.material.SetFloat("_Contrast", value);
            _screenLocate.pcContrast = value;
        }
        /// <summary>
        /// 获取对比度（-1~1）
        /// </summary>
        public float GetContrast()
        {
            return _screenLocate.pcContrast;//_screenLocate.rawImage.material.GetFloat("_Contrast");
        }
        /// <summary>
        /// 设置相机画面分辨率
        /// </summary>
        public void SetCameraResolution(int width, int height)
        {
            if (_uvcManager)
            {
                _uvcManager.DefaultWidth = width;
                _uvcManager.DefaultHeight = height;
            }

            Debug.Log("[InfraredCameraHelper]设置分辨率 SetCameraResolution,width:" + width + " ,height:" + height);
        }
        /// <summary>
        /// 设置相机画面分辨率
        /// </summary>
        public void SetCameraResolutionNew(int width, int height)
        {
            Debug.Log("[InfraredCameraHelper]设置分辨率 SetCameraResolutionNew,width:" + width + " ,height:" + height);
            _screenLocate.Resize(width, height);
        }

        /// <summary>
        /// 设置default分辨率
        /// </summary>
        public void SetHighCameraResolution()
        {
            Vector2 _highResolution = _screenLocate.mUVCCameraInfo.CurrentHighResolution;
            _screenLocate.Resize((int)_highResolution.x, (int)_highResolution.y);
        }
        /// <summary>
        /// 设置Low分辨率
        /// </summary>
        public void SetLowCameraResolution()
        {
            Vector2 _lowResolution = _screenLocate.mUVCCameraInfo.CurrentLowResolution;
            _screenLocate.Resize((int)_lowResolution.x, (int)_lowResolution.y);
        }
        #endregion

        #region 操作接口
        /// <summary>
        /// 单点模式开关
        /// </summary>
        public void SetSinglePoint(bool value)
        {
            _screenLocate.bSinglePoint = value;
        }
        /// <summary>
        /// 是否为单点模式
        /// </summary>
        public bool IsSinglePoint()
        {
            return _screenLocate.bSinglePoint;
        }
        /// <summary>
        /// 设置抖动过滤值
        /// </summary>
        public void SetShakeFilterValue(float value)
        {
            _screenLocate.filterDis = value;
        }
        /// <summary>
        /// 获取抖动过滤值
        /// </summary>
        public float GetShakeFilterValue()
        {
            return _screenLocate.filterDis;
        }
        /// <summary>
        /// 设置亮度过滤阈值
        /// </summary>
        public void SetInfraredLocateBrightnessThreshold(float value)
        {
            _screenLocate.SetInfraredLocateBrightnessThreshold(value);
        }
        /// <summary>
        /// 是否已经定位
        /// </summary>
        public bool IsScreenLoateOK()
        {
            return _screenLocate.IsScreenLoateOK();
        }
        /// <summary>
        /// 是否正在手动定位
        /// </summary>
        public bool IsScreenLocateManualDoing()
        {
            return _screenLocate.IsScreenLocateManualDoing();
        }
        /// <summary>
        /// 进入手动定位
        /// </summary>
        /// <returns>相机画面截图</returns>
        public Texture2D EnterScreenLocateManual()
        {
            return _screenLocate.EnterScreenLocateManual();
        }
        /// <summary>
        /// 退出/完成手动定位
        /// </summary>
        /// <param name="points">定位点（左下、右下、右上、左上）</param>
        public void QuitScreenLocateManual(List<Vector2> points)
        {
            _screenLocate.QuitScreenLocateManual(points);
        }
        /// <summary>
        /// 获取中心点偏移量
        /// </summary>
        /// <param name="inputPoint"></param>
        /// <param name="type"> CameraLocation , ScreenUV</param>
        /// <returns></returns>
        public Vector2 GetCenterOffset(Vector2 inputPoint, string type = "CameraLocation")
        {
            // 获取偏移量
            return _screenLocate.AdjustPointsOffset(inputPoint, type);
        }
        /// <summary>
        /// 初始化一次本地的记录点
        /// </summary>
        public void InitScreenLocateManual()
        {

            //获取本地记录的点
            if (ScreenLocate.GetScreenLocateVectorList())
            {
                Debug.Log("[初始化本地坐标]：" + _screenLocate.PrintVector2List(ScreenLocate.quadUnityVectorList));
                //使用算法顺序点来设置屏幕四边形,定位点(左下，右下，左上，右上)
                _screenLocate.QuadUnityVectorListToScreenQuad(ScreenLocate.quadUnityVectorList);
               // _screenLocate.SyncInfraredDemo();
                InvokeOnUVCPosUpdate(ScreenLocate.quadUnityVectorList);
            }
        }

        /// <summary>
        /// 进入自动定位
        /// </summary>
        public void EnterScreenLocateManualAuto()
        {
            _screenLocate.EnterScreenLocateManualAuto();
        }
        /// <summary>
        /// 修改 Capture ，建议值30
        /// </summary>
        public void SetCapture(int value)
        {
            _screenLocate.SetCapture(value);
        }
        /// <summary>
        /// 修改delay，建议值30
        /// </summary>
        public void SetDelay(int value)
        {
            _screenLocate.SetDelay(value);
        }
        #endregion

        #region 监听事件
        /// <summary>
        /// UVC 相机准备事件
        /// </summary>
        public OnUVCIsReadyEvent OnUVCIsReady;
        public delegate void OnUVCIsReadyEvent(UVCManager.CameraInfo camera);
        public void InvokeOnUVCIsReady(UVCManager.CameraInfo camera)
        {
            try
            {
                OnUVCIsReady?.Invoke(camera);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        /// <summary>
        /// UVC 相机更新事件
        /// </summary>
        public OnUVCIsUpdateEvent OnUVCIsUpdate;
        public delegate void OnUVCIsUpdateEvent();
        public void InvokeOnUVCIsUpdate()
        {
            try
            {
                OnUVCIsUpdate?.Invoke();
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        /// <summary>
        /// UVC 定位点更新事件
        /// </summary>
        public OnUVCPosUpdateEvent OnUVCPosUpdate;
        public delegate void OnUVCPosUpdateEvent(List<Vector2> list);
        public void InvokeOnUVCPosUpdate(List<Vector2> list)
        {
            try
            {
                OnUVCPosUpdate?.Invoke(list);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        /// <summary>
        /// 单点更新事件
        /// </summary>
        public OnPositionUpdateEvent OnPositionUpdate;
        public delegate void OnPositionUpdateEvent(Vector2 position);
        public void InvokeOnPositionUpdate(Vector2 position)
        {
            try
            {
                OnPositionUpdate?.Invoke(position);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        /// <summary>
        /// 双点更新事件
        /// </summary>
        public OnPositionUpdate2Event OnPositionUpdate2;
        public delegate void OnPositionUpdate2Event(Vector2 position, int index);
        public void InvokeOnPositionUpdate2(Vector2 position, int index)
        {
            try
            {
                OnPositionUpdate2?.Invoke(position, index);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        #endregion
    }
}
