﻿using Lovense.UnityKit.Remote;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class RemoteEventController : MonoBehaviour
{

    public static string thisIp;
    public static int thisPort;
    public static bool isSSL = false;
    
    [SerializeField]
    public RemoteEventItem itemObj;

    [SerializeField]
    public Transform root;

    [SerializeField]
    public Text statusText;

   

    private List<RemoteEventItem> uiList = new List<RemoteEventItem>();

    private void Awake()
    {
        LovenseRemote.eventOfApi.AddListener(OnEventOfApi);
        LovenseRemote.eventOfGetToys.AddListener(OnEventOfGetToys);
    }

    private void Start()
    {
        LovenseRemote.GetInstance().AddEventApiListener(thisIp, thisPort,isSSL);
    }

    private void OnEventOfApi(string ip,EventApiType eve)
    {
        if(ip != thisIp)
        {
            return;
        }
        if(eve == EventApiType.EVENT_OPEN)
        {
            statusText.text = "Event opened.";
        } else if(eve == EventApiType.EVENT_GRANTED)
        {
            statusText.text = "Event granted.";
        }
        else if(eve == EventApiType.EVENT_CLOSE)
        {
            statusText.text = "Event closed.";

        }
    }

    private void initUi(List<EventToy> list)
    {
        uiList.Clear();
        root.GetComponent<VerticalLayoutGroup>().transform.DetachChildren();
        for (int i = 0; i < list.Count; i++)
        {
            RemoteEventItem newItem = Instantiate(itemObj, root);
            if (newItem != null)
            {
                newItem.SetData(list[i]);
                uiList.Add(newItem);
            }
        }
    }

    private void OnEventOfGetToys(string ip,List<EventToy> toys) 
    {
        if (ip != thisIp)
        {
            return;
        }
        initUi(toys);
    }

    private void OnDestroy()
    {
        LovenseRemote.eventOfGetToys.RemoveListener(OnEventOfGetToys);
        LovenseRemote.eventOfApi.RemoveListener(OnEventOfApi);
        LovenseRemote.GetInstance().RemoveEventApiListener(thisIp, thisPort);
    }

    public void ClickOnBack()
    {
        SceneManager.LoadScene("LovenseRemote");
    }
}
