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

public class UIWithInteractable : Interactable
{
    [Header("Events:")]
    [SerializeField] private GameEvent onInteraction;
    [SerializeField] private GameEvent onRelease;

    [Header("Listeners:")]
    [SerializeField] private GameEventListener onUIClosed;

    bool isUIOpen = false;

    Transform storedTransform;

    protected override void Awake()
    {
        base.Awake();

        onUIClosed.Response.AddListener(CloseInteraction);
    }

    public override void Interact(bool melee)
    {
        base.Interact(melee);

        if (!melee) return;

        isUIOpen = true;
        onInteraction.Raise();
    }

    public override void OnFocused(Transform playerTransform, PlayerController playerController)
    {
        base.OnFocused(playerTransform, playerController);
        storedTransform = playerTransform;
    }

    protected override void Update()
    {
        if (isFocus && !hasInteracted)
        {
            distance = Vector3.Distance(player.position, interactionTransform.position);

            if (distance <= radius)
            {
                Interact(true);
                hasInteracted = true;
                Debug.Log("Board Interacted-Closeup");
            }
            else if (interactableWithRange)
            {
                if (distance <= rangedRadius)
                {
                    Interact(false);
                    hasInteracted = true;
                }
            }
        }
        else if (isUIOpen)
        {
            distance = Vector3.Distance(storedTransform.position, interactionTransform.position);

            if (distance >= radius)
            {
                OnDeFocus();
                onRelease.Raise();
                Debug.Log("Board Released");
            }
        }
    }

    private void CloseInteraction()
    {
        isUIOpen = false;
        OnDeFocus();
    }
}
