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

// using AndroidJavaClass = UnityEngine.AndroidJNI.AndroidJavaClass;
// using AndroidJavaObject = UnityEngine.AndroidJNI.AndroidJavaObject;

public class PcWebCamera : MonoBehaviour
{
    public int cameraIndex = 0;
    public int width = 320;
    public int height = 240;
    public int fps = 30;
    public string deviceName;

    private WebCamTexture _webCamTexture;
    public WebCamTexture webCamTexture { get => _webCamTexture; set => _webCamTexture = value; }
    public Vector2 Size => new Vector2(width, height);

    public float brightness = 0.0f; // 亮度调整值，范围 -1.0 到 1.0
    public float contrast = 1.0f;   // 对比度调整值，范围 0.0 到 2.0


    private void Awake()
    {
        SceneManager.sceneLoaded += OnSceneLoaded;
    }
    private IEnumerator Start()
    {
        yield return new WaitForEndOfFrame();
        OnClick_Open();
    }
    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        Debug.Log("Scene Loaded: " + scene.name);
        Debug.Log("Load Scene Mode: " + mode);
        // 在场景加载时执行的代码
        //if (BluetoothAim.ins && (BluetoothAim.ins.isMainConnectToHOUYIPRO() || BluetoothAim.ins.isMainConnectToGun()))
        //{
        //    StartCoroutine(RestartWebCam());
        //}
        //else if (scene.name == "Home") {
        //    //没连接设备时候，如果跳回home页面，设置一次
        //    StartCoroutine(RestartWebCam());
        //}
    }
    IEnumerator RestartWebCam()
    {
        yield return new WaitForSecondsRealtime(1); // 延迟 x 秒重启 WebCamTexture
        if (_webCamTexture != null)
        {
            _webCamTexture.Stop();
            _webCamTexture.Play();
        }
    }

    private void Update()
    {
        //if (_webCamTexture)
        //{
        //    width = _webCamTexture.width;
        //    height = _webCamTexture.height;
        //    fps = (int)_webCamTexture.requestedFPS;

        //}
        if (_webCamTexture && _webCamTexture.didUpdateThisFrame)
        {
            width = _webCamTexture.width;
            height = _webCamTexture.height;
            fps = (int)_webCamTexture.requestedFPS;

            AdjustTexture();
            ScreenLocate.Main.setUVCTexture = adjustedTexture;
           // rawImage.texture = ScreenLocate.Main.getUVCTexture;
        }

    }

    public Vector2Int IndexToCoord(int i)
    {
        var y = i / width;
        var x = i % width;
        return new Vector2Int(x, y);
    }

    public int CoordToIndex(int x, int y)
    {
        return y * width + x;
    }

    public void OnClick_Open()
    {

        if (_webCamTexture != null)
        {
            Debug.LogError("开启失败，请先关闭正在使用的摄像头！");
            return;
        }
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            WebCamDevice[] devices = WebCamTexture.devices;
            for (int i = 0; i < devices.Length; i++)
            {
                Debug.Log("devices[" + i + "].name:" + devices[i].name);
            }
            if (devices.Length == 0)
            {
                Debug.LogError("开启失败，没找到可用的摄像头！");
                return;
            }
            if (devices.Length < cameraIndex + 1)
            {
                Debug.LogError("开启失败，没有对应序号的摄像头！");
                return;
            }
            deviceName = devices[cameraIndex].name;
            StartCoroutine(DetectResolutions());
            //Debug.Log("PCWebCamera fps：" + fps + ",size:[" + width + "," + height + "]");
            //_webCamTexture = new WebCamTexture(deviceName, width, height, fps);
            //_webCamTexture.Play();
            //Debug.Log("PCWebCamera成功开启摄像头name：" + deviceName + ",size:[" + _webCamTexture.width + "," + _webCamTexture.height + "]");
            //// 创建一个 Texture2D 用于存储调整后的图像
            ////adjustedTexture = new Texture2D(_webCamTexture.width, _webCamTexture.height);
            //ScreenLocate.Main.WebCamIsReady(_webCamTexture);

        }
        else
        {
            Debug.LogError("开启失败，用户未授予摄像头权限！");
        }
    }
    private int[] widths = { 320, 160 };
    private int[] heights = { 240, 120 };
    private List<Resolution> supportedResolutions = new List<Resolution>();

    private IEnumerator DetectResolutions()
    {
        for (int i = 0; i < 2; i++)
        {
            int _width = widths[i], _height = heights[i];
            _webCamTexture = new WebCamTexture(deviceName, _width, _height, fps);
            _webCamTexture.Play();

            // Wait for a short time to let the webcam initialize
            yield return new WaitForSeconds(2);

            if (_webCamTexture.width > 16 && _webCamTexture.height > 16)
            {
                Debug.Log("Supported resolution: " + _webCamTexture.width + " x " + _webCamTexture.height);
                supportedResolutions.Add(new Resolution { width = _webCamTexture.width, height = _webCamTexture.height });
            }
            else
            {
                Debug.Log("Resolution not supported: " + width + " x " + height);
            }

            _webCamTexture.Stop();
            yield return null;
        }

        // 执行下一步操作，例如选择一个支持的分辨率并启动摄像头
        if (supportedResolutions.Count > 0)
        {
            Resolution selectedResolution = supportedResolutions[0]; // 选择第一个支持的分辨率（你可以根据需要选择不同的分辨率）
            StartWebCam(selectedResolution.width, selectedResolution.height);
        }
        else
        {
            Debug.LogError("No supported resolutions found.");
        }
    }

    private void StartWebCam(int _width, int _height)
    {
        Debug.Log("PCWebCamera fps：" + fps + ",size:[" + _width + "," + _height + "]");
        _webCamTexture = new WebCamTexture(deviceName, _width, _height, fps);
        _webCamTexture.Play();
        Debug.Log("PCWebCamera成功开启摄像头name：" + deviceName + ",size:[" + _webCamTexture.width + "," + _webCamTexture.height + "]");
        ScreenLocate.Main.WebCamIsReady(_webCamTexture);
    }

    public void newWebCamTexture(string name)
    {
        _webCamTexture = new WebCamTexture(name, width, height, fps);
        _webCamTexture.Play();
        //Debug.Log("[newWebCamTexture]成功开启摄像头");
    }

    public void OnClick_Close()
    {
        if (_webCamTexture != null)
        {
            _webCamTexture.Stop();
            _webCamTexture = null;
            Debug.Log("[OnClick_Close]成功关闭摄像头");
        }
    }
    public WebCamTexture newWebCamTexture(int width, int height)
    {
        _webCamTexture = new WebCamTexture(deviceName, width, height, fps);
        _webCamTexture.Play();
        Debug.Log("[newWebCamTexture]成功开启摄像头");
        return _webCamTexture;
    }
    void AdjustBrightnessContrast(Color32[] pixels, float brightness, float contrast)
    {
        float contrastFactor = 1.0f + contrast;
        for (int i = 0; i < pixels.Length; i++)
        {
            Color32 pixel = pixels[i];
            float r = pixel.r / 255.0f;
            float g = pixel.g / 255.0f;
            float b = pixel.b / 255.0f;

            r = Mathf.Clamp01(((r - 0.5f) * contrastFactor + 0.5f) + brightness);
            g = Mathf.Clamp01(((g - 0.5f) * contrastFactor + 0.5f) + brightness);
            b = Mathf.Clamp01(((b - 0.5f) * contrastFactor + 0.5f) + brightness);

            pixel.r = (byte)(r * 255);
            pixel.g = (byte)(g * 255);
            pixel.b = (byte)(b * 255);

            pixels[i] = pixel;
        }
    }

    private Texture2D adjustedTexture;

    private void AdjustTexture()
    {
        Color32[] pixels = _webCamTexture.GetPixels32();
        AdjustBrightnessContrast(pixels, ScreenLocate.Main.pcBrightness, ScreenLocate.Main.pcContrast);

        if (adjustedTexture == null || adjustedTexture.width != _webCamTexture.width || adjustedTexture.height != _webCamTexture.height)
        {
            adjustedTexture = new Texture2D(_webCamTexture.width, _webCamTexture.height);
        }
        adjustedTexture.SetPixels32(pixels);
        adjustedTexture.Apply();
    }
}