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

public class WeaponSelectMenu : MonoBehaviour
{
    public InputActionReference MenuOpenAction;
    public float OpenTime = 1.0f;

    private Vector3 startScale;

    private Coroutine activeCoroutine;

    private void Start()
    {
        startScale = transform.localScale;

        //MenuOpenAction.action.performed += Action_Open;
        //MenuOpenAction.action.canceled += Action_Canceled;

        MenuOpenAction.action.actionMap.Enable();
    }

    private void Action_Open(InputAction.CallbackContext obj)
    {
        if (activeCoroutine == null)
            activeCoroutine = StartCoroutine(OpenMenu(OpenTime, startScale));
    }

    private void Action_Canceled(InputAction.CallbackContext obj)
    {
        if (activeCoroutine != null)
        {
            StopCoroutine(activeCoroutine);
            activeCoroutine = null;
        }

        activeCoroutine = StartCoroutine(OpenMenu(OpenTime, startScale));
    }

    private void Update()
    {
        Vector3 targetScale;

        if (MenuOpenAction.action.ReadValue<float>() > 0.1f)
        {
            targetScale = startScale;
        }
        else
        {
            targetScale = Vector3.zero;
        }

        transform.localScale = Vector3.Lerp(transform.localScale, targetScale, Time.deltaTime * OpenTime);
    }

    private IEnumerator OpenMenu(float duration, Vector3 targetScale)
    {
        Vector3 startScale = transform.localScale;
        Vector3 endScale = targetScale;

        float t = 0.0f;
        while (t < duration)
        {
            t += Time.deltaTime;
            float normalizedTime = t / duration;
            normalizedTime = Easing.Exponential.Out(normalizedTime);

            Vector3 scale = Vector3.Lerp(startScale, endScale, normalizedTime);
            transform.localScale = scale;

            yield return null;
        }
    }
}