using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using MLEM.Startup;
using Newtonsoft.Json;

namespace TouchyTickets {
    public static class Localization {

        public static readonly List<string> NumberFormat = LoadLocalized<List<string>>("NumberFormat", "json5");
        private static readonly Dictionary<string, string> Strings = LoadLocalized<Dictionary<string, string>>("Localization");
        private static readonly Dictionary<string, string> FallbackStrings = Load<Dictionary<string, string>>("Localization");
        private static readonly List<string> News = LoadLocalized<List<string>>("News");
        private static readonly Random Random = new Random();

        public static string Get(string key) {
            if (Strings.TryGetValue(key, out var val))
                return val;
            if (FallbackStrings.TryGetValue(key, out var fallback))
                return fallback;
            return $"?{key}?";
        }

        public static string GetRandomNews() {
            return News[Random.Next(News.Count)];
        }

        private static T LoadLocalized<T>(string name, string extension = "json") {
            var culture = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
            foreach (var path in new[] {$"{name}.{culture}", name}) {
                try {
                    return Load<T>(path, extension);
                } catch (Exception) {
                    // move on to the next path
                }
            }
            throw new ContentLoadException();
        }

        private static T Load<T>(string name, string extension = "json") {
            var path = $"{GameImpl.Instance.Content.RootDirectory}/Localization/{name}.{extension}";
            using (var reader = new JsonTextReader(new StreamReader(TitleContainer.OpenStream(path))))
                return SaveHandler.Serializer.Deserialize<T>(reader);
        }

    }
}