using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
#if UNITY_EDITOR
using UnityEditor;
#endif

// main quest control entity
[System.Serializable]
public class QuestLog {

	public static QuestLog quests = null;

	[XmlArray ("nodes")]
	public List<DialogNode> nodes = new List<DialogNode>();

	public QuestLog () {}

	public DialogNode this[string indexer]{
		get {
			if (nodes != null) {
				foreach(var node in nodes) {
					if (node.id == indexer) {
						return node;
					}
				}
			}
			return null;
		}
	}

	public static QuestLog LoadFromAsset(TextAsset dataAsset) {
		if (dataAsset != null){
			XmlSerializer serialReader = new XmlSerializer(typeof(QuestLog));
			Stream writer = new MemoryStream(dataAsset.bytes);
			var questInfo = (QuestLog)serialReader.Deserialize(writer);
			writer.Close();
			quests = questInfo;
			return questInfo;
		} else {
			Debug.Log("dataAsset not setted");
		}
		return null;
	}
	#if UNITY_EDITOR
	// Save file in resources only from editor
	public static void Save (QuestLog structure, string fileName) {
		XmlSerializer serialWrite = new XmlSerializer(typeof(QuestLog));
		XmlTextWriter writer = new XmlTextWriter (fileName, System.Text.UTF8Encoding.UTF8);
		writer.Formatting = Formatting.Indented;
		writer.IndentChar = ' ';
		serialWrite.Serialize (writer, structure);
		writer.Close();
	}
	public void SaveToAsset(TextAsset dataAsset) {
		Save (this, AssetDatabase.GetAssetPath(dataAsset));
		Debug.Log("Save quests to " + AssetDatabase.GetAssetPath(dataAsset));
	}
	#endif
}
