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

public class DialogueBox : MonoBehaviour
{
	public float letterDelay = 0.1f;
	public TMPro.TextMeshProUGUI textBox;

	public GameObject speaker { get; private set; }
	public string text { get; private set; } = "";

	float timer = 0;
	UIScreen screen;
	int count = 0;

	void Awake() {
		textBox.text = "";
		screen = GetComponent<UIScreen>();
	}

	public void Say(string _text, GameObject _speaker) {
		text = _text;
		speaker = _speaker;
		timer = 0; 
		count = 0;
		gameObject.SetActive(true);
		screen.shown = true;
	}

	void Update() {
		float dt = UIWrangler.deltaTime;

		// Skip stuff when pressed.
		if (count > 0 && Input.GetButtonDown("Fire1")) {
			if (count >= text.Length) {
				text = "";
				speaker = null;
				count = 0;
				screen.shown = false;
			} else {
				count = text.Length;
			}
		}

		// Advance the counter.
		timer += dt;
		while (timer >= letterDelay && count < text.Length) {
			timer -= letterDelay;
			count = Mathf.Min(count+1, text.Length);
		}

		textBox.text = text.Substring(0, count);
	}
}
