using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerUIManager : MonoBehaviour
{

    [SerializeField]
    private InventoryUI Inventory;

    [SerializeField]
    private float AnimationSpeed = 0.5f;

    [SerializeField]
    private BlockInput characterInput;

    [SerializeField]
    private LogicTrayUI TrayUI;

    private Vector3 ShowPosition;
    private Vector3 HidePosition;
    private RectTransform inventoryRect { get { return Inventory.transform as RectTransform; } }

    private void Awake()
    {


        ShowPosition = new Vector3(0, -inventoryRect.rect.height / 2, 0);
        HidePosition = new Vector3(0, inventoryRect.rect.height/2, 0);


        inventoryRect.anchoredPosition = HidePosition;
        TrayUI.SetBlockReader(characterInput.blockReader);
    }

    [ContextMenu("Show")]
    public void OnClick_Show()
    {
        StopAllCoroutines();
        Inventory.UpdateUI();
        StartCoroutine( LerpPosition(inventoryRect, ShowPosition, AnimationSpeed));
    }

    [ContextMenu("Hide")]
    public void OnClick_Hide()
    {
        
        StopAllCoroutines();
        StartCoroutine( LerpPosition(inventoryRect, HidePosition, AnimationSpeed));
    }

    public void OnClick_Toggle()
    {
        if (Vector3.Distance(inventoryRect.anchoredPosition,ShowPosition) < Vector3.Distance(inventoryRect.anchoredPosition, HidePosition))
        {
            Debug.Log("Hiding Menu");
            OnClick_Hide();
        }
        else
        {
            Debug.Log("Showing Menu");
            OnClick_Show();
        }
    }

    public void OnClick_Play() {

        OnClick_Hide();
        characterInput.ReadAll();
    }

    private IEnumerator LerpPosition(RectTransform rt, Vector3 endPosition, float time)
    {

        float elapsedTime = 0;
        Vector3 startPos = rt.anchoredPosition;

        while (elapsedTime < time)
        {
            rt.anchoredPosition = Vector3.Slerp(startPos, endPosition, (elapsedTime / time));
            elapsedTime += Time.deltaTime;
            yield return new WaitForEndOfFrame();
        }

        rt.anchoredPosition = endPosition;
    }

    
}
