using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.InputSystem;

public class NPC : Interactable
{
    public GameObject dialogueBox;
    public TextMeshProUGUI dialogueText;
    public string dialogue;
    public Transform player;
    public InputActionReference interact;
    public bool dialogueStarted;
    public Queue<string> sentences = new Queue<string>();
    public DialogueBranch dialogueBranch;
    public int branchesDone = 0;

    void OnEnable()
    {
        interact.action.started += Interact;
    }
    void OnDisable()
    {
        interact.action.started -= Interact;
    }
    
    public void Interact(InputAction.CallbackContext obj)
    {
        if(!playerInRange) 
        {
            return;
        }
        if(!dialogueStarted)
        {
            StartDialogue();
        }
        else if(dialogueStarted)
        {
            ContinueDialogue();
        }
    }

    public void StartDialogue()
    {
        sentences.Clear();
        foreach(string sentence in dialogueBranch.dialogues[branchesDone].sentences)
        {
            sentences.Enqueue(sentence);
        }
        dialogueBox.SetActive(true); 
        player.gameObject.GetComponent<PlayerMovement>().animator.SetBool("Moving", false);
        player.gameObject.GetComponent<PlayerMovement>().currentState = PlayerState.interact;
        dialogueStarted = true;
        dialogueText.text = dialogue;
        ContinueDialogue();
    }

    public void ContinueDialogue()
    {
        if(sentences.Count == 0)
        {
            EndDialogue();
        }
        else
        {
            StopAllCoroutines();
            string dialogueSentence = sentences.Dequeue();
            StartCoroutine(TypeSentence(dialogueSentence));
        }
    }

    public IEnumerator TypeSentence(string sentence)
    {
        dialogueText.text = "";
        foreach(char letter in sentence.ToCharArray())
        {
            dialogueText.text += letter;
            yield return new WaitForSeconds(1/30f);
        }
    }

    public void EndDialogue()
    {
        dialogueBox.SetActive(false);
        player.gameObject.GetComponent<PlayerMovement>().currentState = PlayerState.idle;
        dialogueStarted = false;
        if(!dialogueBranch.dialogues[branchesDone].finalDialogue)
        {
            branchesDone++;
        }
    }
}