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

[RequireComponent(typeof(Animator))]
public class Door : StateTileAsset
{
	private bool isOpen;
	[SerializeField] private List<Vector2Int> directionsAccessible;

	private bool occupied;
	
	private Animator animator;
	private static readonly int StartTrigger = Animator.StringToHash("Start");
	private static readonly int StopTrigger = Animator.StringToHash("Stop");

	private void Start()
	{
		animator = GetComponent<Animator>();
	}

	public override void SwitchState()
	{
		StartCoroutine(StartAnimation());
	}

	private IEnumerator StartAnimation()
	{
		yield return new WaitUntil(() => !occupied);

		animator.SetTrigger(isOpen ? StopTrigger : StartTrigger);
		AudioController.Play("Door");
		isOpen = !isOpen;
	}

	public override bool CanEnter(Vector2Int comingFrom, Vector2Int goingInto, Orientation orientation)
	{
		foreach (Vector2Int direction in directionsAccessible)
		{
			if (direction == goingInto - comingFrom)
			{
				return isOpen;
			}
		}

		return false;
	}

	public override void OnEnter(GameObject player)
	{
		occupied = true;
	}

	public override void OnLeave(GameObject player)
	{
		occupied = false;
	}
}