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

public class DialogueController : MonoBehaviour {

	#region variables
	private DialogueManager _dialogueManager;

	private CanvasController _canvasController;
	private GameObject _dialogueBox;
	private Text _dialogueTextBox;

	[SerializeField]
	protected DialoguerDialogues _dialogue;

	[SerializeField]
	protected string _textboxName;

	[SerializeField]
	protected KeyCode _keyBinding = KeyCode.None;

	[SerializeField]
	protected bool _continues = false;

	[SerializeField]
	protected bool _enableControls = true;
	#endregion


	#region events
	void Awake () {

		_canvasController = GameObject.FindObjectOfType <CanvasController> ();
		Dialoguer.Initialize ();

	}

	void Start () {

		AddDialogueEvents ();
		Dialoguer.StartDialogue (_dialogue);
		
	}

	void Update () {

		if ((_keyBinding == KeyCode.None && Input.anyKeyDown) || Input.GetKeyDown (_keyBinding)) {
			Dialoguer.ContinueDialogue ();
		}
		
	}
	#endregion


	#region methods
	public void SetManager (DialogueManager dm) {

		_dialogueManager = dm;
		
	}

	public void AddDialogueEvents () {

		Dialoguer.events.onStarted += onDialogueStartedHandler;
		Dialoguer.events.onEnded += onDialogueEndedHandler;
		Dialoguer.events.onTextPhase += onDialogueTextPhaseHandler;

	}

	public void RemoveDialogueEvents () {

		Dialoguer.events.onStarted -= onDialogueStartedHandler;
		Dialoguer.events.onEnded -= onDialogueEndedHandler;
		Dialoguer.events.onTextPhase -= onDialogueTextPhaseHandler;

	}
	#endregion


	#region dialoguer events
	void onDialogueStartedHandler () {

		PlayerMovement.SetUserControl (false);

		_dialogueBox = _canvasController.GetPanel (_textboxName);
		_canvasController.SetPanel (_textboxName, true);
		_dialogueTextBox = _dialogueBox.GetComponentInChildren <Text> ();

		
	}

	void onDialogueEndedHandler () {

		_canvasController.SetPanel (_textboxName, false);

		RemoveDialogueEvents ();

		if (_continues) {

			_dialogueManager.Play ();

		} else {

			if (_enableControls) {
				StartCoroutine (EnableControls ());
			}

		}

		if (_dialogueManager.NextEvent != null && !_continues) {
			_dialogueManager.NextEvent ();
			_dialogueManager.NextEvent = null;
		}

	}

	void onDialogueTextPhaseHandler (DialoguerTextData data) {
		
		_dialogueTextBox.text = data.text;

	}
	#endregion


	#region coroutines
	IEnumerator EnableControls () {
		yield return new WaitForSeconds (0.25f);
		PlayerMovement.SetUserControl (true);
	}
	#endregion

}
