using General;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace CXMLDecompiler
{
    public static class CXMLSymbols
    {
        private static Dictionary<string, string> Symbols = new Dictionary<string, string>();

        public static string LookupKey(string key)
        {
            if (!Symbols.ContainsKey(key.ToLowerInvariant()))
                return key.ToLowerInvariant();
            else
                return Symbols[key.ToLowerInvariant()];
        }

        public static string LookupId(string id)
        {
            foreach (KeyValuePair<string, string> Symbol in Symbols)
            {
                if (Symbol.Value == id)
                {
                    return Symbol.Key;
                }
            }

            if (id.Length == 8)
            {
                try
                {
                    Int32.Parse(id, NumberStyles.HexNumber);
                    return id;
                }
                catch (Exception) { };
            }


            return Tools.GenerateShortHash(Encoding.UTF8.GetBytes(id));

        }

        public static void Init(string SymbolFile)
        {
            string[] lines = File.ReadAllText(SymbolFile).Replace("\r", "").Split('\n');

            foreach(string line in lines)
            {
                if (line.StartsWith("#"))
                    continue;
                if (line == "")
                    continue;

                if(line.Contains(' '))
                {
                    string key = "";
                    string id = "";

                    foreach (string opt in line.Split(' '))
                    {
                        if (opt.Contains(":"))
                        {
                            string[] kv = opt.Split(':');
                            if (kv[0].ToLowerInvariant().StartsWith("key"))
                                key = kv[1];
                            if (kv[0].ToLowerInvariant().StartsWith("id"))
                                id = kv[1];
                        }
                    }

                    if (key.Contains("("))
                        key = key.Substring(0, key.IndexOf("("));
                    if (id.Contains(","))
                        id = id.Substring(0, id.IndexOf(","));

                    Console.WriteLine("Reading Symbol .. key: " + key + " id: " + id);

                    Symbols.Add(key.ToLowerInvariant(), id);
                }
            }
        }
    }
}
