using System;
using Grid;
using UnityEngine;

public class Door : MonoBehaviour, IInteractable {
    private static readonly int open = Animator.StringToHash("IsOpen");
    [SerializeField] private bool isOpen;
    private Animator animator;
    private Action onInteractionComplete;
    private float timer;
    private bool IsActive { get; set; }
    private GridPosition GridPosition { get; set; }

    private bool IsOpen {
        get => isOpen;
        set {
            isOpen = value;
            animator.SetBool(open, IsOpen);
            Pathfinding.Instance.SetWalkableGridPosition(GridPosition, isOpen);
        }
    }

    private void Awake() => animator = GetComponent<Animator>();

    private void Start() {
        GridPosition = LevelGrid.Instance.GetGridPosition(transform.position);
        LevelGrid.Instance.SetInteractableAtGridPosition(GridPosition, this);
        IsOpen = isOpen;
    }

    private void Update() {
        if (!IsActive) return;
        timer -= Time.deltaTime;
        if (timer > 0f) return;
        IsActive = false;
        onInteractionComplete();
    }

    public void Interact(Action newOnInteractionComplete) {
        onInteractionComplete = newOnInteractionComplete;
        IsActive = true;
        timer = .5f;
        IsOpen = !IsOpen;
    }
}