using UnityEngine;
using Cinemachine;
using ftt.Core.Managing;

public class PlayerInteractions : MonoBehaviour
{
    [SerializeField] CinemachineVirtualCamera playerCam;
    [SerializeField] float distance;
    [SerializeField] KeyCode hidingInteractionKey;
    [SerializeField] KeyCode torchInteractionKey;
    [SerializeField] Animator animator;
    [SerializeField] GameObject uiDot;
    [SerializeField] GameObject fireEffect;

    RaycastHit hit;
    IInteractable interactable;

    private void Awake()
    {
        fireEffect.SetActive(false);
        uiDot.gameObject.SetActive(false);
    }

    private void Start()
    {
        GameManager.GetManager.SetPlayerInteractions(this);
    }

    private void Update()
    {
        if (Input.GetKeyDown(torchInteractionKey) && fireEffect.gameObject.activeSelf)
        {
            animator.SetTrigger("TurnOff");
            fireEffect.SetActive(false);
            GameManager.GetManager.IsTorchOpen = false;
            return;
        }

        CheckForInteraction();
    }

    void CheckForInteraction()
    {
        if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out hit, distance))
        {
            if (hit.collider.CompareTag("Torch"))
            {
                if (uiDot.gameObject.activeSelf != true)
                { uiDot.gameObject.SetActive(true); }

                if (Input.GetKeyDown(torchInteractionKey))
                {
                    animator.SetTrigger("TurnOn");
                    fireEffect.SetActive(true);
                    GameManager.GetManager.IsTorchOpen = true;
                }
            }
            else if (hit.collider.CompareTag("Interactable"))
            {
                if (uiDot.gameObject.activeSelf != true)
                { uiDot.gameObject.SetActive(true); }

                if (Input.GetKeyDown(hidingInteractionKey) && interactable == null)
                {
                    if (hit.transform.TryGetComponent<IInteractable>(out interactable))
                    {
                        interactable.InteractWithObject();
                        interactable = null;
                    }
                }
            }
            else
            { uiDot.gameObject.SetActive(false); }
        }
        else
        { uiDot.gameObject.SetActive(false); }
    }

    //Called when hiding
    public void ForceTurnOffTorch()
    {
        if (!fireEffect.activeSelf) return;

        animator.SetTrigger("TurnOff");
        fireEffect.SetActive(false);
        GameManager.GetManager.IsTorchOpen = false;
        return;
    }
}
