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

public static class Dialog
{
    public static string language = "BR";
    public static DialogManager manager;
    public delegate void FinalTrigger(int a);
    static char lineBreak = ']';
    static char nameBreak = ';';
    static Dictionary<string, DiagScene> scenes;

    public static void Initialize()
    {
        var go = new GameObject();
        go.name = "Dialog Manager";
        manager = go.AddComponent<DialogManager>();
        manager.skin = Resources.Load<GUISkin>("Padron_Cabron");
        scenes = new Dictionary<string, DiagScene>();

        // load all scenes
        var lang = language == "BR" ? "*_BR.txt" : "*_US.txt";
        var files = Directory.GetFiles(Application.dataPath + "/Dialogues/", lang);
        foreach (string file in files)
            LoadScene(file);
    }

    public static void PlayScene(string key,Texture photo = null)
    {
        if (!scenes.ContainsKey(key))
        {
            MonoBehaviour.print("dialogue does not exists");
            return;
        }
        manager.PrepareScene(scenes[key]);
        manager.photo = photo;
    }
    
    //public static void LoadScene(string key, string encodedText)
    public static void LoadScene(string fullPath)
    {
        StreamReader reader = new StreamReader(fullPath);
        string encodedText = reader.ReadToEnd();
        reader.Close();

        var scene = new DiagScene();
        var str = encodedText.Split(lineBreak);
        scene.name = new string[str.Length];
        scene.text = new string[str.Length];

        for (var i = 0; i < str.Length; i++)
        {
            /*if (str[i][0] == '*')
            {

            }
            else*/
            if (str[i].IndexOf(nameBreak) < 0)
            {
                scene.name[i] = "";
                scene.text[i] = str[i];
            }
            else
            {
                var s = str[i].Split(nameBreak);
                scene.name[i] = s[0];
                scene.text[i] = s[1];
                if (scene.text[i][0] == ' ')
                    scene.text[i].Remove(0, 1);
            }
        }
        var key = Path.GetFileName(fullPath);
        scenes.Add(key.Remove(key.Length-7,7), scene);
    }
    
    public static void UnloadScene(string key) {
        scenes.Remove(key);
    }

    public struct DiagScene
    {
        public string[] name;
        public string[] text;
        public FinalTrigger trigger;
    }
    
}
