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

public class SpeechBubbleController : MonoBehaviour
{
	//Editor variables
	float textTypeSpeed;

	//Working variables
	public static SpeechBubbleController instance;
	int currentPage;
	int characterPointer;
	string[] tutorialText = {
		"Ah the new Trainee Deity Appeasement Admin, you took your time! ",
		"You've picked a hell of a day to start, the Old Gods are kicking up a fuss so I'm going to have my hands full. ",
		"I need you to look after the Lesser Gods... you know, the kind of weird ones. ",
		"It's really not hard, just match up the offerings to the God's tastes. Get it right, they'll be happy, get it wrong and, well you're a smart lad! ",
		"Damn, looks like a sacrifice is escaping, I've got to go! ",
		"Listen, you (might be) fine, just try and appease as many Gods as possible with each offering and avoid getting the village set on fire OK? "
	};
	Text textRef;
	float lastCharTypeTime;

	void Reset()
	{
		textTypeSpeed = 0.3f;
	}

	void Awake()
	{
		instance = this;
		textRef = transform.GetComponentInChildren<Text>();
	}

	void Start()
	{
		currentPage = characterPointer = 0;
		toggleScreenVisibility(false);
	}

	void startTypingOutNewPage(int pageNumberToTypeOut)
	{
		currentPage = pageNumberToTypeOut;
		characterPointer = 0;
		AudioController.instance.playSFX(AudioController.audioClips.mumble);
	}

	void Update()
	{
		CanvasGroup grp = transform.parent.GetComponent<CanvasGroup>();
		if (!grp.interactable || Time.time - lastCharTypeTime < textTypeSpeed) { return; }

		if (characterPointer < tutorialText[currentPage].Length-1)
		{
			characterPointer++;
			textRef.text = tutorialText[currentPage].Substring(0, characterPointer);
			lastCharTypeTime = Time.time;
		}
	}

	public void toggleScreenVisibility(bool isVisible)
	{
		CanvasGroup grp = transform.parent.GetComponent<CanvasGroup>();
		grp.alpha = isVisible ? 1.0f : 0.0f;
		grp.interactable = grp.blocksRaycasts = isVisible;

		if (isVisible) { AudioController.instance.playSFX(AudioController.audioClips.mumble); }
	}

	public void continueButtonClicked()
	{
		AudioController.instance.playSFX(AudioController.audioClips.click);

		if (characterPointer < tutorialText[currentPage].Length-1)
		{
			characterPointer = tutorialText[currentPage].Length - 1;
			lastCharTypeTime = Time.time;
			textRef.text = tutorialText[currentPage];
		}
		else if (currentPage < tutorialText.Length-1) { startTypingOutNewPage(currentPage+1); }
		else { toggleScreenVisibility(false); }
	}
}
