using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class LocalizationManager : MonoBehaviour {

	public  static LocalizationManager instance;

	public string defaultLang = "Rus/"; //язык по-умолчанию

    public Dictionary<string, string>[] localizedTexts = new Dictionary<string, string>[3];

	private bool isReady = false;
	private string missingTextString = "Localized text not found";

	void Awake () 
	{
		if (instance == null) 
		{
			instance = this;
		}
		else if (instance != this)
		{
			Destroy (gameObject);
		}

		DontDestroyOnLoad (gameObject);
	}

    /*////////////////////////////////*/

	void Start()
	{
        DataController.instance.Load ();
		LoadLocalizedText (defaultLang);
	}

    //Загрузка файлов локализации
	public void LoadLocalizedText(string fileName)
	{
        for (int j = 0; j < localizedTexts.Length; j++)
        {
            localizedTexts[j] = new Dictionary<string, string>();

            string filePath = Path.Combine(Application.streamingAssetsPath, fileName + j + "_text.json");

            if (File.Exists(filePath))
            {
                string dataAsJson = File.ReadAllText(filePath);
                LocalizationData loadedData = JsonUtility.FromJson<LocalizationData>(dataAsJson);

                for (int i = 0; i < loadedData.items.Length; i++)
                {
                    localizedTexts[j].Add(loadedData.items[i].key, loadedData.items[i].value);
                }

                Debug.Log(j + " Data loaded, dictionary contains: " + localizedTexts[j].Count + " entries");
            }
            else
            {
                Debug.LogError("Cannot find file!");
            }
        }
			
		isReady = true;
	}

	/*////////////////////////////////*/

	public string GetLocalizedValue(string key, int i)
	{
		string result = missingTextString;
		if (localizedTexts[i].ContainsKey (key)) 
		{
			result = localizedTexts[i] [key];
		}

		return result;
	}
	
	public bool GetIsReady()
	{
		return isReady;
	}

    //Установка языка
	public void SetLanguge(string lang)
	{
		defaultLang = lang;
	}
}
