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

public class SolaceProFeedbackPanel : MonoBehaviour
{
    [SerializeField]
    Text topBottom;
    [SerializeField]
    RectTransform bg, fg;
    [SerializeField]
    Text postionText;
    Coroutine coroutine;
    string toyId;

    public void SetToyId(string toyId)
    {
        this.toyId = toyId;
    }

    // Start is called before the first frame update
    void Start()
    {
        LovenseAndroidSDK.GetInstance().SubscribeSolaceProPositionGotEvent(OnGetPosition);
        LovenseAndroidSDK.GetInstance().SubscribeSolaceProFeedbackDataGotEvent(OnGetResult);
        LovenseAndroidSDK.GetInstance().AddSolaceProListener(toyId);
    }

    private void OnGetPosition(int direction, int pos)
    {
        fg.sizeDelta = new Vector2(fg.rect.width * pos / 100f, bg.rect.height);
        postionText.text = pos + "";
        if (direction == 0)
        {
            topBottom.text = "↓↓";
        }
        else
        {
            topBottom.text = "↑↑";
        }
    }

    private void OnGetResult(List<FeedBackDataForSolacePro> args)
    {
        if(coroutine != null)
        {
            StopCoroutine(coroutine);
        }
        coroutine = StartCoroutine(ShowTouch(args));
    }

    private IEnumerator ShowTouch(List<FeedBackDataForSolacePro> arg0)
    {
        int len = arg0.Count;
        for(int i=0;i < len;i++)
        {
            fg.sizeDelta = new Vector2(bg.rect.width* arg0[i].position / 100f, bg.rect.height);
            postionText.text = arg0[i].position + "";
            if (arg0[i].direction == 0)
            {
                topBottom.text = "↓↓";
            } else
            {
                topBottom.text = "↑↑";
            }
            yield return new WaitForSeconds(0.1f);
        }
    }

    public void ClickOnStartFeedback()
    {
        LovenseAndroidSDK.GetInstance().SendCommandWithoutValue(toyId, LovenseCommandType.START_FEEDBACK);
    }

    public void ClickOnStopFeedback()
    {
        LovenseAndroidSDK.GetInstance().SendCommandWithoutValue(toyId, LovenseCommandType.STOP_FEEDBACK);
    }

    public void ClickOnGetPoition()
    {
        LovenseAndroidSDK.GetInstance().SendCommandWithoutValue(toyId, LovenseCommandType.GET_POSITION);
    }

    private void OnDestroy()
    {
        LovenseAndroidSDK.GetInstance().UnsubscribeSolaceProPositionGotEvent(OnGetPosition);
        LovenseAndroidSDK.GetInstance().UnsubscribeSolaceProFeedbackDataGotEvent(OnGetResult);
    }

   
}
