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

[RequireComponent(typeof(Animator))]
public class Teleporter : TileAsset
{
	[SerializeField] private List<Transform> targets;
	[SerializeField] private List<Vector2Int> directionsAccessible;
	[SerializeField] private float animationTime;
	[SerializeField] private List<Orientation> allowedOrientations;
	[SerializeField] private string soundName;
	private int currentTargetIndex;
	private Animator animator;
	private static readonly int StartTrigger = Animator.StringToHash("Start");


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

	public override bool CanEnter(Vector2Int comingFrom, Vector2Int goingInto, Orientation orientation)
	{
		if (allowedOrientations.Any() && !allowedOrientations.Contains(orientation))
		{
			return false;
		}

		if (directionsAccessible.Any() && directionsAccessible.Any(d => d == goingInto - comingFrom))
		{
			return false;
		}

		return true;
	}

	public override void OnEnter(GameObject player)
	{
		animator.SetTrigger(StartTrigger);
		if (!string.IsNullOrEmpty(soundName)) AudioController.Play(soundName);
		player.SetActive(false);
		currentTargetIndex++;
		StartCoroutine(OnCompleteAnimation(player));
	}

	private IEnumerator OnCompleteAnimation(GameObject player)
	{
		yield return new WaitForSeconds(animationTime);
		var current = targets[currentTargetIndex % targets.Count];
		player.transform.position = current.transform.position;
		player.transform.rotation = current.transform.rotation;
		player.SetActive(true);
	}

	public override void OnLeave(GameObject player)
	{
	}
}