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

public class VendorController : Interactable
{
    [SerializeField] private VendorData vendorData;

    public VendorData VendorData => vendorData;

    [Header("Events:")]
    [SerializeField] private GameEvent_VendorData onVendorInteracted;
    [SerializeField] private GameEvent onVendorReleased;

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

    bool isUIOpen = false;

    Transform storedTransform;

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

        onVendorUIClosed.Response.AddListener(CloseInteraction);
    }

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

        if (!melee) return;

        isUIOpen = true;
        onVendorInteracted.Raise(vendorData);
    }

    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($"vendor {this.transform.name} 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();
                onVendorReleased.Raise();
                Debug.Log($"vendor {this.transform.name} released");
            }
        }
    }

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