using UnityEngine;

/// <summary>
/// Trigger zone that starts a subtitle JSON sequence on a linked SubtitleSequencePlayer.
/// Put this on the zone collider object, and link the player on your empty object.
/// </summary>
[RequireComponent(typeof(Collider))]
public class SubtitleTriggerZone : MonoBehaviour
{
    [Header("References")]
    [SerializeField] private SubtitleSequencePlayer subtitlePlayer;
    [SerializeField] private TextAsset subtitleJson;

    [Header("Playback")]
    [SerializeField] private float initialDelay = 0f;
    [SerializeField] private bool oneShot = true;

    private bool m_hasPlayed;

    private void Reset()
    {
        Collider col = GetComponent<Collider>();
        col.isTrigger = true;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (!IsPlayer(other))
            return;

        if (oneShot && m_hasPlayed)
            return;

        if (subtitlePlayer == null)
            return;

        if (subtitlePlayer.TryPlay(subtitleJson, initialDelay))
            m_hasPlayed = true;
    }

    private bool IsPlayer(Collider other)
    {
        if (other.CompareTag("Player"))
            return true;

        if (other.GetComponentInParent<PlayerMovement>() != null)
            return true;

        return false;
    }
}
