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

public class PatternV2Panel : MonoBehaviour
{

    [SerializeField]
    public Text syncTimeText;
    [SerializeField]
    Slider intervalValue, intervalTime, loopTimes;

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

    Func<RemoteAppData> getCurrentRemote;
    Func<List<LovenseRemoteToy>> getCurrentToys;
    private float syncTime;
    void Start()
    {
        LovenseRemote.onPatternV2Event.AddListener(OnPatternV2Result);
        LovenseRemote.onPatternSyncTimeEvent.AddListener(OnGetSyncTime);
    }

    private void OnPatternV2Result(PatternV2_REQ_TYPE arg0, ControlToysResult arg1)
    {
        Debug.Log("get response " + arg0.ToString() + ",code:" + arg1.code + ",type:" + arg1.type);
    }

    private void OnGetSyncTime(float arg0)
    {
        syncTime = arg0;
        syncTimeText.text = arg0 + "s";
    }

    public void SetCurrentRemoteCallback(Func<RemoteAppData> get)
    {
        getCurrentRemote = get;
    }

    public void SetCurrentToyCallback(Func<List<LovenseRemoteToy>> get)
    {
        getCurrentToys = get;
    }

    public void ClickOnSetup()
    {
        RemoteAppData current = getCurrentRemote();
        int startValue = 0;
        int startTime = 0;
        addPatternList = new List<PositionPatternValue>();
        for (int i = 0; i < loopTimes.value; i++)
        {
            PositionPatternValue position = new PositionPatternValue();
            position.time = startTime;
            startTime += (int)intervalTime.value;
            position.position = startValue % 100;
            startValue += (int)intervalValue.value;
            addPatternList.Add(position);
        }
        LovenseRemote.GetInstance().SendPatternSetup(current.domain,current.httpsPort, addPatternList, true);
    }

    public void ClickOnSyncTime()
    {
        RemoteAppData current = getCurrentRemote();
        LovenseRemote.GetInstance().GetPatternV2SyncTime(current.domain, current.httpsPort, true);
    }

    public void ClickOnStart()
    {
        RemoteAppData currentApp = getCurrentRemote();
        List<LovenseRemoteToy> toys = getCurrentToys();
        if(toys != null)
        {
            foreach(LovenseRemoteToy toy in toys)
            {
                LovenseRemote.GetInstance().StartPatternV2(currentApp.domain, currentApp.httpsPort);
            }
        }
    }

    public void ClickOnStop()
    {
        RemoteAppData currentApp = getCurrentRemote();
        List<LovenseRemoteToy> toys = getCurrentToys();
        if (toys != null)
        {
            foreach (LovenseRemoteToy toy in toys)
            {
                LovenseRemote.GetInstance().StopPatternV2(currentApp.domain, currentApp.httpsPort,  toyId: toy.id,true);
            }
        }
    }
}
