using System.Collections;
using UnityEngine;
using UnityEngine.UI;

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

public class ZIMWebCamera : MonoBehaviour
{
    public int cameraIndex = 1;
    public int width = 1280;
    public int height = 720;
    public int fps = 60;
    public RawImage rawImage;
    public RawImage rawImageSize;
    public MaintainAspectRatio maintainAspectRatio;
    private WebCamTexture _webCamTexture;
    public WebCamTexture webCamTexture { get => _webCamTexture; }
    public Vector2 Size => new Vector2(width, height);

    public Text logText;

    public Transform mParent;


    private IEnumerator Start()
    {
        yield return new WaitForEndOfFrame();
        OnClick_Open();
    }

    private void Awake()
    {

    }

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

            rawImageSize.texture = rawImage.texture;
            //rawImageSize.SetNativeSize();
            maintainAspectRatio.AdjustSize();

            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);
                this.logText.text += "devices[" + i + "].name:" + devices[i].name + "\n";
            }
            if (devices.Length == 0)
            {
                Debug.LogError("开启失败，没找到可用的摄像头！");
                return;
            }
            if (devices.Length < cameraIndex + 1)
            {
                Debug.LogError("开启失败，没有对应序号的摄像头！");
                return;
            }
            string deviceName = devices[cameraIndex].name;
            _webCamTexture = new WebCamTexture(deviceName, width, height, fps);

            //try
            {
                _webCamTexture.Play();
               // if (rawImage) rawImage.texture = _webCamTexture;
                Debug.Log("ZIMWebCamera fps：" + fps + ",size:[" + width + "," + height + "]");
                ScreenLocate.Main.WebCamIsReady(_webCamTexture);

               // rawImage.texture = ScreenLocate.Main.getUVCTexture;

                Debug.Log("ZIMWebCamera成功开启摄像头name：" + deviceName + ",size:[" + _webCamTexture.width + "," + _webCamTexture.height + "]");
            }
            //catch (System.Exception e)
            //{
            //    Debug.Log("摄像头开启失败 " + deviceName + ", 可能有其他软件占用, " + e.Message);
            //}

            //o0WebCam = new o0.Project.WebCam(_webCamTexture);
            /*
            Task.Run(() => {
                if(_webCamTexture.didUpdateThisFrame)
            });/**/
        }
        else
        {
            Debug.LogError("开启失败，用户未授予摄像头权限！");
        }
    }


    public void newWebCamTexture(string name)
    {
        _webCamTexture = new WebCamTexture(name, width, height, fps);
        _webCamTexture.Play();
        if (rawImage) rawImage.texture = _webCamTexture;

    }

    public void OnClick_Close()
    {
        if (_webCamTexture != null)
        {
            _webCamTexture.Stop();
            _webCamTexture = null;
            if (rawImage) rawImage.texture = null;
            Debug.Log("成功关闭摄像头");
            //o0WebCam.Dispose();
            //o0WebCam = null;
        }
    }

    public void OnClick_ScreenLocateManual()
    {
        Debug.Log("OnClick_ScreenLocateManual");

    }


    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();
    }
}