using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Resources;

namespace BoFilTest.Utils
{
    public class TranslationKey
    {
        public TranslationKey(string resourceKey)
        {
            this.ResourceKey = resourceKey;
        }

        public string ResourceKey { get; }
    }

    class Translated
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private static ResourceManager rm = new ResourceManager("BoFilTest.Translations", Assembly.GetExecutingAssembly());
        private static Dictionary<string, string> dynamicDictionary;

        public static string NotYet(string text, params object[] args)
        {
            return String.Format(text, args);
        }

        public static string FromKey(TranslationKey key, params object[] args)
        {
            return FromKey(key.ResourceKey, args);
        }

        public static string FromKey(string key, params object[] args)
        {
            return String.Format(GetUninterpolatedFor(key), args);
        }

        private static string GetUninterpolatedFor(string key)
        {
            PrepareDynamicDictionary();

            string dynamicValue = "";
            if (dynamicDictionary.TryGetValue(key, out dynamicValue))
                return dynamicValue;

            var value = rm.GetString(key);
            if (value == null)
                return key;
            return value;
        }

        private static void PrepareDynamicDictionary()
        {
            if (dynamicDictionary != null)
                return;
            
            dynamicDictionary = new Dictionary<string, string>();
            try
            {
                using (ResXResourceReader resxReader = new ResXResourceReader("Translations.resx"))
                {
                    foreach (DictionaryEntry entry in resxReader)
                    {
                        dynamicDictionary.Add((string)entry.Key, (string)entry.Value);
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error("Unable to read dynamic translations: {0}", e.Message);
            }            
        }
    }
}
