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

public class Door : MonoBehaviour, IInteractable
{
    public enum DoorState {
        Open,
        Closed,
    }
    [SerializeField] private DoorState IsOpen;
    private Animator animator;
    private GridPosition gridPosition;
    private Action onInteractionComplete;
    private float timer;
    private bool isActive;

    private void Awake() {
        animator = GetComponent<Animator>();
    }
    private void Start() {
        gridPosition = LevelGrid.Instance.GetGridPosition(transform.position);
        LevelGrid.Instance.SetInteractableAtGridPosition(gridPosition, this);

        if (IsOpen == DoorState.Open) {
            OpenDoor();
        } else {
            CloseDoor();
        }
    }
    public void Interact(Action onInteractionComplete) {
        this.onInteractionComplete = onInteractionComplete;
        isActive = true;
        timer = 0.5f;
        if (IsOpen == DoorState.Open) {
            CloseDoor();
        } else {
            OpenDoor();
        }
    }

    private void Update() {
        if (!isActive) {
            return;
        }

        timer -= Time.deltaTime;
        if (timer <= 0f) {
            isActive = false;
            onInteractionComplete();
        }
    }
    public void OpenDoor() {
        IsOpen = DoorState.Open;
        animator.SetBool("IsOpen", true);
        Pathfinding.Instance.SetIsWalkableGridPosition(gridPosition,true);
    }
    public void CloseDoor() {
        IsOpen = DoorState.Closed;
        animator.SetBool("IsOpen", false);
        Pathfinding.Instance.SetIsWalkableGridPosition(gridPosition,false);
    }
}