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

public class OSXLovenseDetailItem : MonoBehaviour
{
    // Start is called before the first frame update
    [SerializeField]
    public GameObject feedbackGameobject;
    [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;
    LovenseOSXToy toy;
    List<LovenseOSXToy> toys;
    private bool isConnect = false;

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

    [SerializeField]
    public Transform toysRoot;

    [SerializeField]
    public GameObject errorPanel;
    [SerializeField]
    public Text errorText;





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

    private void Awake()
    {
        LovenseOSXTools.onOSXGetBatteryEvent.AddListener(onCallBackBatteryListenerFunc);
        LovenseOSXTools.onOSXGetTypeEvent.AddListener(onCallBackDeviceTypeListenerFunc);
        LovenseOSXTools.onOSXConnectEvent.AddListener(onToysConnectEvent);
        LovenseOSXTools.onOSXCommandEvent.AddListener(onToysCommandEvent);
        LovenseOSXTools.onGetToyDataReportingEnabled.AddListener(onToysDataReporting);
    }

   

    private void onToysDataReporting(string id)
    {
        if (this.toy != null && this.toy.identifier == id)
        {
            feedbackGameobject.SetActive(true);
        }
        else if (this.toys != null && (this.toys.Find(t => t.identifier == id) != null))
        {
            feedbackGameobject.SetActive(true);
        }
    }

    void Start()
    {
        functionButton.color = Color.gray;
        patternButton.color = Color.gray;
        presetButton.color = Color.gray;
        this.toy = OSXGlobal.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);
        
           
            isConnect = LovenseOSXTools.GetInstance().IsConnected(toy.identifier);
            if (!isConnect)
            {
                connect.text = "Connect";
                LovenseOSXTools.GetInstance().ConnectToys(new List<string>() { toy.identifier });
            }
            else
            {
                connect.text = "DisConnect";
                if (this.toy.isSupportDataReporting)
                {
                    feedbackGameobject.SetActive(true);
                }
                if (this.toy.type != null || this.toy.type != "")
                {
                    devicenfo.text = toy.type;
                }
                else
                {
                    LovenseOSXTools.GetInstance().SendFunctionWithoutValue(toy.identifier, LovenseCommandType.GET_DEVICETYPE);
                }
                LovenseOSXTools.GetInstance().SendFunctionWithoutValue(toy.identifier, LovenseCommandType.GET_BATTERY);
            }
            
            deviceMac.text = toy.macAddress;
            deviceVersion.text = toy.version + "";
            deviceBattery.text = toy.battery + "%";
            
        } else
        {
            this.toys = OSXGlobal.GetInstance().thisToys;
            isConnect = false;

            connect.text = "Connect";
            foreach (LovenseOSXToy toy in toys)
            {
                if(toy.isConnected)
                {
                    isConnect = true;
                    connect.text = "DisConnect";
                }
                if (toy.isSupportDataReporting)
                {
                    feedbackGameobject.SetActive(true);
                }
            }
            List<string> names = OSXGlobal.GetInstance().thisToysNames;
            //LovenseAndroidSDK.GetInstance().connectToy(toyIds, onConnectListener);
            InitToys(toys, names);
            toysNames.gameObject.SetActive(true);
            toyDetails.gameObject.SetActive(false);
        }

    }

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

            OSXToyCheckItem 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 (this.toy != null && this.toy.identifier == toyId)
        {
            if (status == 0)
            {
                ShowErrorText("execute command (" + msg + ") failed!");
            }
        }

    }

    public void onToysConnectEvent(string toyId,int status,string msg)
    {
        if(this.toy != null && toyId == this.toy.identifier)
        {
            if(status == 0)
            {
                if(toyId!= null)
                {
                    isConnect = false;
                    connect.text = "Connect";
                }
                  
            } else if(status == 1)
            {
                isConnect = true;
                connect.text = "DisConnect";
                LovenseOSXTools.GetInstance().SendFunctionWithoutValue(toyId, LovenseCommandType.GET_DEVICETYPE) ;
                LovenseOSXTools.GetInstance().SendFunctionWithoutValue(toyId, LovenseCommandType.GET_BATTERY);
            } else if(status == -1)
            {
                if(isConnect && toyId != null)
                {
                    isConnect = false;
                    ShowErrorText("connect error:" + msg);
                    connect.text = "Connect";
                }
                
            }
        } else if(toys != null && (toys.Find(t=>t.identifier==toyId)) != null) 
        {
            if (status == 0)
            {

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

            }
        }
    }

   



    public void onCallBackDeviceTypeListenerFunc(string toyId, string type)
    {
        if(toy == null )
        {
            return;
        }
        if(toyId == toy.identifier)
        {

            LovenseOSXToy toy = LovenseOSXTools.allToys.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)
    {
        if (this.toy != null && this.toy.identifier == toyId)
        {
            deviceBattery.text = battery + "%";
        } 
    }

   


    private void LateUpdate()
    {

    }

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

    }



    public void ClickOnFeedback()
    {
        SceneManager.LoadScene("LovenseOSXScene2");
    }


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

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

            }
        } else
        {
            if(connect.text == "Connect")
            {
                connect.text = "DisConnect";
                LovenseOSXTools.GetInstance().ConnectToys(GetSelectedToy(true));
            } else
            {
                LovenseOSXTools.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(toy != null)
            LovenseOSXTools.GetInstance().StopAll(new List<string>() { toy.identifier });
        else
            LovenseOSXTools.GetInstance().StopAll(GetSelectedToy(false));
    }

    public void AddPattern()
    {
        if (patternContent.childCount - 2 >= 50)
        {
            ShowErrorText("must be less than 50");
            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.VIBTATE;
                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(toy != null)
                LovenseOSXTools.GetInstance().SendFunctions(new List<string>() { toy .identifier }, commands, ts, rt1, pt);
            else
                LovenseOSXTools.GetInstance().SendFunctions(GetSelectedToy(false), commands, ts, rt1, pt);
        }
        else
        {
            ShowErrorText("the toy is not connected");
        }
    }

    public List<string> GetSelectedToy(bool isConnectOperate)
    {
        List<string> selected = new List<string>();
        foreach(OSXToyCheckItem item in checkItems)
        {
            if(item.IsCheck())
            {
                string id = item.GetToyId();
                if(isConnectOperate)
                {
                    selected.Add(item.GetToyId());
                } else if (LovenseOSXTools.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.VIBTATE);
            }
            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(addList.Count < 1)
            {
                ShowErrorText("please add the pattern");
                return;
            }
            if (toy != null)
                LovenseOSXTools.GetInstance().SendPattern(new List<string>() { toy.identifier }, typeList, addList,  pattern_sec.value, (int)pattern_ms.value);
            else
                LovenseOSXTools.GetInstance().SendPattern(GetSelectedToy(false) , typeList, addList,  pattern_sec.value, (int)pattern_ms.value);
        }
        else
        {
            ShowErrorText("no toy is connected");
        }
    }

    public void SendPreset()
    {
        if (isConnect)
        {
            int mode = (int)preset_slider.value;
            float timeSec = preset_time.value;
            if (mode == 0)
            {
                ShowErrorText("plaease input mode value!");
                return;
            }
            if(toy != null)
            {
                LovenseOSXTools.GetInstance().SendPreset(new List<string>() { toy.identifier }, mode, timeSec);
            } else
            {
                LovenseOSXTools.GetInstance().SendPreset(GetSelectedToy(false), mode, timeSec);
            }
        }
        else
        {
            ShowErrorText( "no toyis connected!");
        }
    }

    
    private void ShowErrorText(string error)
    {
        errorPanel.SetActive(true);
        errorText.text = error;
    }

    public void ClickOnError()
    {
        errorPanel.SetActive(false);
    }

    private void OnDestroy()
    {
        LovenseOSXTools.onOSXGetBatteryEvent.RemoveListener(onCallBackBatteryListenerFunc);
        LovenseOSXTools.onOSXGetTypeEvent.RemoveListener(onCallBackDeviceTypeListenerFunc);
        LovenseOSXTools.onOSXConnectEvent.RemoveListener(onToysConnectEvent);
        LovenseOSXTools.onGetToyDataReportingEnabled.RemoveListener(onToysDataReporting);
    }
}
