using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
[System.Serializable]
public class LocalizationData 
{
    public LocalizationItem[] text;
	public LocalizationPopupItem[] popup_text;
}

[System.Serializable]
public class LocalizationItem
{
    public string key;
    public string value;
}

[System.Serializable]
public class LocalizationPopupItem
{
	public string key;
	public string title;
	public string message;
}

public class PopupContent 
{
	public string title;
	public string message;

	public PopupContent(string title, string message){
		this.title 		= title;
		this.message	= message;
	}
}
public class LocalizationManager : MonoBehaviour {

	public static LocalizationManager instance;

	private Dictionary<string, string> localizedText;
	private Dictionary<string, PopupContent> localizedPopupText;
	private bool isReady = false;
	private string missingTextString = "Localized text not found";

	private string fileName = "gametext_en";		// gametext_ko
	// Use this for initialization
	void Awake() {
		Debug.Log("LocalizationManager Awake!!!");
		if (instance == null) {
			instance = this;
			LoadLocalizedText();
		} else if (instance != this)
		{
			Destroy(gameObject);
		}
		DontDestroyOnLoad(gameObject);
	}
	
	public void LoadLocalizedText()
	{
		localizedText 		= new Dictionary<string, string>();
		localizedPopupText 	= new Dictionary<string, PopupContent>();
		TextAsset txt = (TextAsset)Resources.Load(fileName, typeof(TextAsset));
		Debug.Log("Load Localized Text");
		string content = txt.text;
		


		if (!string.IsNullOrEmpty(content)) {

			LocalizationData loadedData = JsonUtility.FromJson<LocalizationData> (content);

			for (int i = 0 ; i < loadedData.text.Length; i++) {
				localizedText.Add(loadedData.text[i].key, loadedData.text[i].value);
			}
			
			for (int i = 0 ; i < loadedData.popup_text.Length; i++) {
				PopupContent popupContent = new PopupContent(loadedData.popup_text[i].title, loadedData.popup_text[i].message);
				localizedPopupText.Add(loadedData.popup_text[i].key, popupContent);
			}
			isReady = true;
		} else {
			Debug.LogError("Cannot find file!");
		}
	}


	public string GetLocalizedValue(string key)
	{
		string result = missingTextString;

		if (localizedText.ContainsKey(key)){
			result = localizedText[key];
		}

		return result;
	}

	public PopupContent GetLocalizedPopupValue(string key)
	{
		PopupContent result = new PopupContent(missingTextString, missingTextString);

		if (localizedPopupText.ContainsKey(key)) 
		{
			result = localizedPopupText[key];
		}
		return result;
	}

	public bool GetIsReady()
	{
		return isReady;
	}
}
