using Lovense.UnityKit;
using Lovense.UnityKit.iOS;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class iOSLovenseDetailItem : MonoBehaviour
{
    // Start is called before the first frame update
    [SerializeField]
    public GameObject toyDetails, toysNames;
    [SerializeField]
    public Text devicenfo, deviceMac, deviceVersion, deviceBattery;

    [SerializeField]
    public Text connect;
    [SerializeField]
    public Slider vibrate, ratote, pump, thrusting, fingering, timeSec, runningTime, pauseTime, pattern_ms, pattern_sec, preset_slider, preset_time;
    [SerializeField]
    public Image  functionButton, patternButton, presetButton;
    [SerializeField]
    public GameObject functionPanel, patternPanel, presetPanel;

    [SerializeField]
    public Toggle vibrateTog, ratoteTog, pumpTog, thrustTog, fingerTg;
    [SerializeField]
    public SliderItem addPatternObj;
    [SerializeField]
    public Transform patternContent;
    LovenseiOSToy toy;
    string toyId;
    List<string> toyIds;
    private bool isConnect = false;

    public List<iOSToyCheckItem> checkItems = new List<iOSToyCheckItem>();
    [SerializeField]
    public iOSToyCheckItem itemObject;

    [SerializeField]
    public Transform toysRoot;





    List<SliderItem> addPatternList = new List<SliderItem>();

    private void Awake()
    {
        LovenseiOSSDK.oniOSGetBatteryEvent.AddListener(onCallBackBatteryListenerFunc);
        LovenseiOSSDK.oniOSGetTypeEvent.AddListener(onCallBackDeviceTypeListenerFunc);
        LovenseiOSSDK.oniOSConnectEvent.AddListener(onToysConnectEvent);
        LovenseiOSSDK.oniOSCommandEvent.AddListener(onToysCommandEvent);
    }

    void Start()
    {
        functionButton.color = Color.gray;
        patternButton.color = Color.gray;
        presetButton.color = Color.gray;
        this.toy = iOSGlobal.GetInstance().thisToy;
        //this.toys = new LovenseiOSToy();
        //this.toys.name = "111111";
        //this.toys.identifier = "sssss";
        //this.toys.type = "sssss";
        //this.toys.macAddress = "sssss";
        //this.toys.isConnected = true;
        onFunctionClick();
        if (this.toy != null)
        {
            toysNames.gameObject.SetActive(false);
            toyDetails.gameObject.SetActive(true);
            this.toyId = toy.identifier;
        
           
            isConnect = LovenseiOSSDK.GetInstance().IsConnected(toyId);

            if (!isConnect)
            {
                LovenseiOSSDK.GetInstance().ConnectToys(new List<string>() { toyId });
            }
            else
            {
                LovenseiOSSDK.GetInstance().SendFunctionWithoutValue(toyId, new LovenseCommand() { type=LovenseCommandType.GET_DEVICETYPE});
                LovenseiOSSDK.GetInstance().SendFunctionWithoutValue(toyId, new LovenseCommand() { type= LovenseCommandType.GET_BATTERY});
            }
            devicenfo.text = toy.type;
            deviceMac.text = toy.macAddress;
            deviceVersion.text = toy.version + "";
            deviceBattery.text = toy.battery + "%";
            isConnect = LovenseiOSSDK.GetInstance().IsConnected(toyId);
            if (!isConnect)
            {
                connect.text = "Connect";
            }
            else
            {
                connect.text = "DisConnect";

            }
        } else
        {
            this.toyId = null;
            this.toyIds = iOSGlobal.GetInstance().thisToys;
            isConnect = false;

            connect.text = "Connect";
            foreach (string id in toyIds)
            {
                if(LovenseiOSSDK.GetInstance().IsConnected(id))
                {
                    isConnect = true;

                    connect.text = "DisConnect";
                }
            }
            List<string> names = iOSGlobal.GetInstance().thisToysNames;

            //LovenseAndroidSDK.GetInstance().connectToy(toyIds, onConnectListener);
            InitToys(toyIds, names);
            toysNames.gameObject.SetActive(true);
            toyDetails.gameObject.SetActive(false);
        }

    }

    public void InitToys(List<string> ids, List<string> names)
    {
        for (int i = 0; i < ids.Count; i++)
        {

            iOSToyCheckItem newObject = GameObject.Instantiate(itemObject, toysRoot);
            if (newObject != null)
            {
                //AndroidToyCheckItem newView = newObject.GetComponent<AndroidToyCheckItem>();
                newObject.gameObject.SetActive(true);
                newObject.SetCheckData(names[i], ids[i]);
                checkItems.Add(newObject);
            }
            else
            {
                //Debug.LogError("error");
            }
        }
    }

    public void onToysCommandEvent(string toyId, int status, string msg)

    {
        if (status == 0)
        {
            LovenseiOSSDK.ShowiOSAlert("LovenseTip", "execute command (" + msg + ") failed!","Sure");
        }
        else if (status == -1) {
            LovenseiOSSDK.ShowiOSAlert("LovenseTip", "execute command failed!"+msg, "Sure");
        }

    }

    public void onToysConnectEvent(string toyId,int status,string msg)
    {
        if(this.toyId != null && toyId == this.toyId)
        {
            if(status == 0)
            {
                if(toyId!= null)
                {
                    isConnect = false;
                    connect.text = "Connect";
                }
                  
            } else if(status == 1)
            {
                isConnect = true;
                connect.text = "DisConnect";
                LovenseiOSSDK.GetInstance().SendFunctionWithoutValue(toyId, new LovenseCommand() { type = LovenseCommandType.GET_DEVICETYPE });
                LovenseiOSSDK.GetInstance().SendFunctionWithoutValue(toyId, new LovenseCommand() { type = LovenseCommandType.GET_BATTERY });
            } else if(status == -1)
            {
                if(isConnect && toyId != null)
                {
                    isConnect = false;
                    LovenseiOSSDK.ShowiOSAlert("LovenseTip", "connect error:" + msg, "Sure");
                    connect.text = "Connect";
                }
                
            }
        } else if(this.toyIds.Contains(toyId)) 
        {
            if (status == 0)
            {

            }
            else if (status == 1)
            {
                isConnect = true;
                connect.text = "DisConnect";
                LovenseiOSSDK.GetInstance().SendFunctionWithoutValue(toyId, new LovenseCommand() { type = LovenseCommandType.GET_DEVICETYPE });
                LovenseiOSSDK.GetInstance().SendFunctionWithoutValue(toyId, new LovenseCommand() { type = LovenseCommandType.GET_BATTERY });
            }
            else if (status == -1)
            {

            }
        }
    }

   



    public void onCallBackDeviceTypeListenerFunc(string toyId, string type)
    {
        if(toyId == this.toyId)
        {

            LovenseiOSToy toy = LovenseiOSSDK.iOSToys.Find(t => t.identifier == toyId);
            devicenfo.text = type;
            deviceMac.text = toy.macAddress;
            deviceVersion.text = toy.version + "";
        //LovenseiOSSDK.getInstance().UpdateToysInfo(lovenseToy);
        }
    }

    public void onCallBackBatteryListenerFunc(string toyId, int battery)
    {
        deviceBattery.text = battery + "%";
    }

   


    private void LateUpdate()
    {

    }

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

    }




    

    public void Back()
    {
        Scene currentScene = SceneManager.GetActiveScene();
        int previousSceneIndex = currentScene.buildIndex - 1;
        SceneManager.LoadScene("LovenseiOSScene0");
    }

    public void onConnectClick()
    {
        if(toyId != null)
        {
            isConnect = LovenseiOSSDK.GetInstance().IsConnected(toyId);
            if (!isConnect)
            {
                LovenseiOSSDK.GetInstance().ConnectToys(new List<string>() { toyId });
                //connect.text = "DisConnect";
                //isConnect = true;
            }
            else
            {
                LovenseiOSSDK.GetInstance().DisConnectToys(new List<string>() { toyId });
                //connect.text = "Connect";
                //isConnect = false;

            }
        } else
        {
            if(connect.text == "Connect")
            {
                connect.text = "DisConnect";
                LovenseiOSSDK.GetInstance().ConnectToys(GetSelectedToy(true));
            } else
            {
                LovenseiOSSDK.GetInstance().DisConnectToys(GetSelectedToy(true));
                connect.text = "Connect";
            }
        }
       
    }

    public void onCommandClick()
    {
        //commandFunction.color = Color.cyan;
        //functionButton.color = Color.gray;
        //patternButton.color = Color.gray;
        //presetButton.color = Color.gray;

        //commandPanel.SetActive(true);
        //functionPanel.SetActive(false);
        //patternPanel.SetActive(false);
        //presetPanel.SetActive(false);
    }

    public void onFunctionClick()
    {
        functionButton.color = Color.cyan;
        patternButton.color = Color.gray;
        presetButton.color = Color.gray;

        functionPanel.SetActive(true);
        patternPanel.SetActive(false);
        presetPanel.SetActive(false);
    }

    public void onPatternClick()
    {
        functionButton.color = Color.gray;
        patternButton.color = Color.cyan;
        presetButton.color = Color.gray;

        functionPanel.SetActive(false);
        patternPanel.SetActive(true);
        presetPanel.SetActive(false);
    }

    public void onPresetClick()
    {
        //commandFunction.color = Color.gray;
        functionButton.color = Color.gray;
        patternButton.color = Color.gray;
        presetButton.color = Color.cyan;

        //commandPanel.SetActive(false);
        functionPanel.SetActive(false);
        patternPanel.SetActive(false);
        presetPanel.SetActive(true);
    }

    public void onStopClick()
    {
        if(toyId != null)
            LovenseiOSSDK.GetInstance().StopAll(new List<string>() { toyId });
        else
            LovenseiOSSDK.GetInstance().StopAll(GetSelectedToy(false));
    }

    public void AddPattern()
    {
        if (patternContent.childCount - 2 >= 50)
        {
            LovenseiOSSDK.ShowiOSAlert("LovenseTip","must be less than 50","OK");
            return;
        }
        SliderItem newPattern = Instantiate(addPatternObj, patternContent);
        newPattern.gameObject.SetActive(true);
        addPatternList.Add(newPattern);
        newPattern.transform.SetSiblingIndex(patternContent.childCount - 2);
    }

    public void ReducePattern()
    {
        if (addPatternList.Count > 0)
        {
            SliderItem del = addPatternList[addPatternList.Count - 1];
            del.transform.SetParent(null);
            Destroy(del);
            addPatternList.RemoveAt(addPatternList.Count - 1);
        }
    }

    public void OnSendFunctionClick()
    {
        List<LovenseCommand> commands = new List<LovenseCommand>();
        int vb = (int)(vibrate.value);
        int rt = (int)(ratote.value);
        int pm = (int)(pump.value);
        int th = (int)(thrusting.value);
        int fg = (int)(fingering.value);
        float ts = timeSec.value;
        float rt1 = runningTime.value;
        float pt = pauseTime.value;
        if (isConnect)
        {
            //if (ts == 0)
            //{
            //    LovenseiOSSDK.ShowiOSAlert("LovenseTip","please input the correct value of time","OK");
            //    return;
            //}
            if(vb != 0)
            {
                LovenseCommand command = new LovenseCommand();
                command.type = LovenseCommandType.VIBRATE;
                command.value = vb;
                commands.Add(command);
            }

            if (rt != 0)
            {
                LovenseCommand command = new LovenseCommand();
                command.type = LovenseCommandType.ROTATE;
                command.value = rt;
                commands.Add(command);
            }

            if (pm != 0)
            {
                LovenseCommand command = new LovenseCommand();
                command.type = LovenseCommandType.PUMP;
                command.value = pm;
                commands.Add(command);
            }

            if (th != 0)
            {
                LovenseCommand command = new LovenseCommand();
                command.type = LovenseCommandType.THRUSTRING;
                command.value = th;
                commands.Add(command);
            }

            if (fg != 0)
            {
                LovenseCommand command = new LovenseCommand();
                command.type = LovenseCommandType.FINGERING;
                command.value = fg;
                commands.Add(command);
            }
            //if (fg != 0)
            //{
            //    LovenseAndroidCommand command = new LovenseAndroidCommand();
            //    command.type = LovenseAndroidCommand.LovenseAndroidCommandType.FINGERING;
            //    command.value = fg;
            //    commands.Add(command);
            //}
            if(toyId != null)
                LovenseiOSSDK.GetInstance().SendFunctions(new List<string>() { toyId}, commands, ts, rt1, pt);
            else
                LovenseiOSSDK.GetInstance().SendFunctions(GetSelectedToy(false), commands, ts, rt1, pt);
        }
        else
        {
            LovenseiOSSDK.ShowiOSAlert("LovenseTip", "the toy is not connected", "Sure");
        }
    }

    public List<string> GetSelectedToy(bool isConnectOperate)
    {
        List<string> selected = new List<string>();
        foreach(iOSToyCheckItem item in checkItems)
        {
            if(item.IsCheck())
            {
                string id = item.GetToyId();
                if(isConnectOperate)
                {
                    selected.Add(item.GetToyId());
                } else if (LovenseiOSSDK.GetInstance().IsConnected(id))
                {
                    selected.Add(item.GetToyId());
                }
            }
        }
        return selected;
    }

    public void OnSendPattern()
    {
        if (isConnect)
        {
            List<LovenseCommandType> typeList = new List<LovenseCommandType>();
            if(vibrateTog.isOn)
            {
                typeList.Add(LovenseCommandType.VIBRATE);
            }
            if (ratoteTog.isOn)
            {
                typeList.Add(LovenseCommandType.ROTATE);
            }
            if (pumpTog.isOn)
            {
                typeList.Add(LovenseCommandType.PUMP);
            }
            if (thrustTog.isOn)
            {
                typeList.Add(LovenseCommandType.THRUSTRING);
            }
            if (fingerTg.isOn)
            {
                typeList.Add(LovenseCommandType.FINGERING);
            }


            List<int> addList = new List<int>();
            for (int i = 0; i < addPatternList.Count; i++)
            {
                int add = addPatternList[i].GetValue();
                addList.Add(add);
            }
            //if (pattern_sec.value == 0)
            //{
            //    LovenseiOSSDK.ShowiOSAlert("LovenseTip","please input the correct value of time","Sure");
            //    return;
            //}
            if(addList.Count < 1)
            {
                LovenseiOSSDK.ShowiOSAlert("LovenseTip", "please add the pattern","Sure");
                return;
            }
            if (toyId != null)
                LovenseiOSSDK.GetInstance().SendPattern(new List<string>() { toyId }, typeList, addList,  pattern_sec.value, (int)pattern_ms.value);
            else
                LovenseiOSSDK.GetInstance().SendPattern(GetSelectedToy(false) , typeList, addList,  pattern_sec.value, (int)pattern_ms.value);
        }
        else
        {
            LovenseiOSSDK.ShowiOSAlert("LovenseTip", "the toy's power is off", "Sure");
        }
    }

    public void SendPreset()
    {
        if (isConnect)
        {
            int mode = (int)preset_slider.value;
            float timeSec = preset_time.value;
            if (mode == 0)
            {
                LovenseiOSSDK.ShowiOSAlert("LovenseTip", "plaease input mode value!", "Sure");
                return;
            }
            if(toyId != null)
            {
                LovenseiOSSDK.GetInstance().SendPreset(new List<string>() { toyId }, mode, timeSec);
            } else
            {
                LovenseiOSSDK.GetInstance().SendPreset(GetSelectedToy(false), mode, timeSec);
            }
        }
        else
        {
            LovenseiOSSDK.ShowiOSAlert("LovenseTip", "the toy's power is off", "Sure");
        }
    }

    private void OnDestroy()
    {
        LovenseiOSSDK.oniOSGetBatteryEvent.RemoveListener(onCallBackBatteryListenerFunc);
        LovenseiOSSDK.oniOSGetTypeEvent.RemoveListener(onCallBackDeviceTypeListenerFunc);
        LovenseiOSSDK.oniOSConnectEvent.RemoveListener(onToysConnectEvent);
    }
}
