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

public class UITest : MonoBehaviour
{
    public GameObject togglePrefab; // 拖入一个Toggle预设体

    public GameObject sliderPrefab; // 拖入一个Slider预设体
    public GameObject spawnPoint;

    public UVCManager mUVCManager;
    public UVCManager.CameraInfo cameraInfo;


    [SerializeField] Dropdown _dropdownResolution;


    //自动曝光
    bool bAutoAE = false;
    Slider CTRLAEABSSlider; 
    //PU_BRIGHTNESS（亮度）
    //PU_CONTRAST(对比度)
    //PU_HUE(色调)
    //PU_SATURATION（饱和度）
    //PU_SHARPNESS(锐度)
    //PU_GAMMA(伽玛)
    //PU_WB_TEMP(白平衡温度)
    //PU_WB_COMPO（白平衡分量）
    //PU_BACKLIGHT(背光补偿)
    //PU_GAIN（增益）
    //PU_POWER_LF（电源线频率）
    //PU_HUE_AUTO（色相，自动）
    //PU_WB_TEMP_AUTO(白平衡温度，自动)
    //PU_WB_COMPO_AUTO（白平衡分量，自动）
    //PU_DIGITAL_MULT（数字乘法器）
    //PU_DIGITAL_LIMIT（数字乘数限制）
    //PU_AVIDEO_STD（模拟视频标准）
    //PU_AVIDEO_LOCK(模拟视频锁定状态)
    //PU_CONTRAST_AUTO（对比度，自动）
    string[] sliderNameArray = new string[]{
        "自动曝光模式",
        "曝光时间(绝对)",

        "亮度", //
        "对比度",
        "色调",
        "饱和度",
        "锐度",
        "白平衡温度",
        //"白平衡分量",
        "伽玛",
        "背光补偿",
        "增益" };

    string[] sliderStrArray = new string[]{
        "CTRL_AE",
        "CTRL_AE_ABS",

        "PU_BRIGHTNESS",
        "PU_CONTRAST",
        "PU_HUE",
        "PU_SATURATION",
        "PU_SHARPNESS",
        "PU_GAMMA",
        "PU_WB_TEMP",
        //"PU_WB_COMPO",
        "PU_BACKLIGHT",
        "PU_GAIN" };

    public void initSlider()
    {

        for (int i = 0; i < sliderStrArray.Length; i++)
        {
            string typeStr = sliderStrArray[i];
           // UInt64 _VALUE = cameraInfo.GetTypeByName(typeStr);
            //不支持的，跳过
            bool bContains = cameraInfo.ContainsKey(typeStr);
            if (!bContains) continue;
            if (typeStr == "CTRL_AE")
            {
                //如果是自动曝光，使用toggle 选择
                GameObject toggleObject = Instantiate(togglePrefab, spawnPoint.transform);
                toggleObject.SetActive(true);
                Text labelObj = toggleObject.transform.Find("Label").GetComponent<Text>();
                labelObj.text = sliderNameArray[i];
                Toggle toggle = toggleObject.GetComponent<Toggle>();

                UVCCtrlInfo _AEInfo = cameraInfo.GetInfo(typeStr);
                bAutoAE = _AEInfo.def == 8 ? true : false;

                toggle.onValueChanged.AddListener((bool bValue) =>
                {
                    if (typeStr == "CTRL_AE")
                    {
                        //开关控制是否自动曝光
                        bAutoAE = bValue;
                        if(CTRLAEABSSlider) CTRLAEABSSlider.interactable = !bAutoAE;
                        int _value = bValue ? 8 : 1;
                        //Debug.Log("_value " + _value);
                        cameraInfo.SetValue(typeStr, _value);
                    }

                });
            }
            else
            {
                //其余使用slider
                GameObject sliderObject = Instantiate(sliderPrefab, spawnPoint.transform);
                sliderObject.SetActive(true);
                Slider slider = sliderObject.GetComponent<Slider>();

                if (typeStr == "CTRL_AE_ABS") {
                    CTRLAEABSSlider = slider;
                    slider.interactable = !bAutoAE;
                }

                Text textObj = sliderObject.transform.Find("text").GetComponent<Text>();
                Text titleTextObj = sliderObject.transform.Find("title").GetComponent<Text>();
                titleTextObj.text = sliderNameArray[i];//类型名字
                if (slider != null)
                {

                    UVCCtrlInfo _UVCCtrlInfo = cameraInfo.GetInfo(typeStr);
                    slider.minValue = _UVCCtrlInfo.min;
                    slider.maxValue = _UVCCtrlInfo.max;
                    slider.wholeNumbers = true; 
                    slider.value = _UVCCtrlInfo.def;
                    // 可以添加更多的配置，例如添加监听事件等
                    textObj.text = _UVCCtrlInfo.def + "";

                    //如果有存储到初始值，设置一次
                    //cameraInfo.SetValue(BRIGHTNESS_VALUE, xxx);

                    slider.onValueChanged.AddListener((newValue) =>
                    {
                        var _value = Mathf.FloorToInt(newValue);
                        textObj.text = _value + "";
                        //Debug.Log("Slider value changed to: " + newValue + " from " + _VALUE);
                        cameraInfo.SetValue(typeStr, _value);
                    });
                }
            }
        }
    }

    public void getDevices()
    {
        //List<UVCManager.CameraInfo> cameraInfos = mUVCManager.GetAttachedDevices();
        //for (int i = 0; i < cameraInfos.Count; i++)
        //{
        //    Debug.Log("Device Name " + i + ":" + cameraInfos[i].DeviceName);
        //}
        //cameraInfo = cameraInfos[0];
    }
    void Awake()
    {

        //if (mUVCDrawer)
        //    mUVCDrawer.StartPreviewAction += UVCIsReady;



        _dropdownResolution.onValueChanged.AddListener(v =>
        {
            SetResolution(v);
        });
    }

    void OnDestroy()
    {
        //if (mUVCDrawer)
        //    mUVCDrawer.StartPreviewAction -= UVCIsReady;
    }
    //public void OnInitUVCManager()
    //{
    //    mUVCManager.onStartUVCManager();
    //}

    //public void onStartView() {
    //    mUVCManager.onStartPreview(cameraInfo.device);
    //}
    //public void onStopView()
    //{
    //    mUVCManager.onStopPreview(cameraInfo.device);
    //}
    /**
     * UVC機器とのネゴシエーション時に
     * H.264を優先してネゴシエーションするかどうか
     * Android実機のみ有効
     * true:	H.264 > MJPEG > YUV
     * false:	MJPEG > H.264 > YUV
     */
    public bool PreferH264 = false;
    private const int FRAME_TYPE_MJPEG = 0x000007;
    private const int FRAME_TYPE_H264 = 0x000014;
    void SetResolution(int optionIndex)
    {
        _dropdownResolution.SetValueWithoutNotify(optionIndex);
        switch (optionIndex)
        {
            case 0:
                Resize(1280, 960);
                break;
            case 1:
                Resize(1280, 720);
                break;
            case 2:
                Resize(640, 480);
                break;
            case 3:
                Resize(640, 360);
                break;
            case 4:
                Resize(320, 240);
                break;
        }
    }
    void Resize(int width,int height) {
        if (cameraInfo == null) return;
        int[] frameTypes = {
                    PreferH264 ? FRAME_TYPE_H264 : FRAME_TYPE_MJPEG,
                    PreferH264 ? FRAME_TYPE_MJPEG : FRAME_TYPE_H264,
                };
        foreach (var frameType in frameTypes)
        {
            Debug.Log("Resize frameType:" + frameType + " = " + width + " : "+ height);
            //if (UVCManager.onResize(cameraInfo.device.id, frameType, width, height) == 0)
            //{
            //    Debug.Log("frameType:" + frameType);
            //    break;
            //}
        }
    }

    public void UVCIsReady(Texture texture)
    {
        getDevices();


        //Dictionary<UInt64, UVCCtrlInfo> keyValuePairs = cameraInfo.getCtrlInfos();
        //foreach (KeyValuePair<UInt64, UVCCtrlInfo> kvp in keyValuePairs)
        //{
        //    Debug.Log($"Key: {kvp.Key}, Value: {kvp.Value}");
        //}

        //List<UInt64> list = cameraInfo.GetCtrls();
        //for (int i = 0; i < list.Count; i++)
        //{
        //    int value = cameraInfo.GetValue(list[i]);

        //    UVCCtrlInfo uVCCtrlInfo = cameraInfo.GetInfo(list[i]);

        //    Debug.Log(i + "= Ctrls:" + list[i] + ",Value:" + value + "，info:" + uVCCtrlInfo.ToString());
        //}

        //Int32 value = cameraInfo.GetValue(0x00000001);
        //Debug.Log("Brightness:"+value);

        initSlider();
    }

    public void permission() {
        // 检查权限
        bool bCamera = Permission.HasUserAuthorizedPermission(Permission.Camera);
        Debug.Log("bCamera:"+ bCamera);
        if (!bCamera)
        {
            // 请求权限
            Permission.RequestUserPermission(Permission.Camera);
        }

    }


    public void OpenAppSettings()
    {
        AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");

        AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent",
            "android.settings.APPLICATION_DETAILS_SETTINGS");
        AndroidJavaObject uri = new AndroidJavaClass("android.net.Uri").CallStatic<AndroidJavaObject>("fromParts",
            "package", currentActivity.Call<string>("getPackageName"), null);
        intent.Call<AndroidJavaObject>("setData", uri);
        currentActivity.Call("startActivity", intent);
    }
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}
