﻿using Lovense.UnityKit;
using Lovense.UnityKit.Dongle;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using static Lovense.UnityKit.Dongle.LovenseDongleTools;

public class ScrollItemClick : MonoBehaviour
{

    [SerializeField]
    public Toggle toggle;

    LovenseDongleToy thisToy;

    private void Awake()
    {
        LovenseDongleTools.onConnectChangeEvent.AddListener(OnConnectedChange);
        LovenseDongleTools.onGetTypeEvent.AddListener(OnGetType);
        LovenseDongleTools.onGetBatteryEvent.AddListener(OnGetBattery);
    }

    private void OnGetBattery(string id, string battery)
    {
        if(thisToy != null && thisToy.id == id )
        {
            this.transform.Find("battery").GetComponent<Text>().text = battery;
        }
    }

    private void OnDestroy()
    {
        LovenseDongleTools.onConnectChangeEvent.RemoveListener(OnConnectedChange);
        LovenseDongleTools.onGetTypeEvent.RemoveListener(OnGetType);
        LovenseDongleTools.onGetBatteryEvent.RemoveListener(OnGetBattery);
    }

    private void OnGetType(string id,string type)
    {
        if (thisToy != null && this.thisToy.id == id)
        {
            this.transform.Find("type").GetComponent<Text>().text =type;
        }
    }

    public void OnConnectedChange(string toyId,bool connected)
    {
        if(thisToy != null && this.thisToy.id == toyId)
        {
            this.transform.Find("connected").GetComponent<Text>().text =  "connected:"+connected;
        } 
    }


    // Start is called before the first frame update
    void Start()
    {
        
    }

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

    public void OnThisToyClick()
    {
        if (LovenseDongleTools.GetInstance().isScanning())
        {
            LovenseDongleController.GetInstancce().ShowError("scanning toys now!please try later.");
            return;
        }
        DongleGlobal.GetInstance().thisToys = new List<LovenseDongleToy>() { thisToy};
        SceneManager.LoadScene("LovenseDongle1");
    }
    
    public void SetToyData(LovenseDongleToy data)
    {
        this.gameObject.SetActive(true);
        this.thisToy = data;
        this.transform.Find("name").GetComponent<Text>().text = data.name;
        this.transform.Find("id").GetComponent<Text>().text = data.id;
        this.transform.Find("type").GetComponent<Text>().text = data.type;
        this.transform.Find("connected").GetComponent<Text>().text = "connected:"+ data.isConnected;
        this.transform.Find("battery").GetComponent<Text>().text = data.battery + "";

    }

    public bool IsCheck()
    {
        return toggle.isOn;
    }

    public LovenseDongleToy GetToyData()
    {
        return this.thisToy;
    }


}
