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

public class DialogUI : BaseUI
{
	[SerializeField]Text questionLabel = null; // Set from editor
	[SerializeField]Button[] answerPanels = new Button[6]; // Set from editor
	[SerializeField]Text[] answerLabels = new Text[6]; // Set from editor
	
	Dialog currentDialog = null;
	DialogNode currentNode = null;

	public void SelectAnswer(int select)
	{
		if (currentNode != null)
		{
			currentNode = currentDialog [currentNode.GetNextNode (select)];
			SetDialogContent (currentNode);
		}
	}

	void SetDialogContent(string question, string[] answers)
	{
		if (questionLabel)
		{
			questionLabel.text = question.Replace("з", "3"); // hack
		}
		for (int i = 0; i < answerPanels.Length; i++)
		{
			if (answerPanels[i] != null)
			{
				if (i < answers.Length)
				{
					answerPanels[i].gameObject.SetActive(true);
					if (answerLabels[i] != null)
					{
						answerLabels[i].text = answers[i].Replace("з", "3"); // hack
					}
				}
				else
				{
					answerPanels[i].gameObject.SetActive(false);
				}
			}
		}
	}

	void SetDialogContent(DialogNode node)
	{
		if (node != null)
		{
			node.InvokeActions ();
			SetDialogContent(node.question, node.GetAnswersList());
		}

	}

	void SetDialog(Dialog newDialog)
	{
		currentDialog = newDialog;
		currentNode = newDialog.nodes [0];
		if (currentNode != null)
		{
			SetDialogContent(currentNode);
		}
	}

	protected override void OnShow ()
	{
		Dialog dialog = new Dialog ();
		DialogNode node = new DialogNode ();
		node.id = "start";
		node.question = "Привет, ты кто?";
		node.answers = new DialogAnswer[] {
			new DialogAnswer() {answer = "заново", nextNodeId = "start", actions = new TriggerAction[] {
					new TriggerAction(TriggerAction.Type.SetTriggerValue, "grib", 1)
				}
			},
			new DialogAnswer() {answer = "Я гриб", nextNodeId = "end", conditions = new Condition[] {
					new Condition("grib", Condition.Type.Equal, 0)
				}},
			new DialogAnswer() {answer = "Я не гриб", nextNodeId = "end"}
		};
		node.actions = new TriggerAction[] {
			new TriggerAction(TriggerAction.Type.SetTriggerValue, "end", 1)
		};
		dialog.nodes.Add (node);
//		Dialog.Save (dialog, Application.dataPath + "/Resources/Quests/dummy.xml");

		if (dialog != null)
		{
			SetDialog(dialog);
		}
	}
}
