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 {

        private static readonly Dictionary<string, string> Strings = LoadLocalized<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) {
            return Strings.TryGetValue(key, out var ret) ? ret : $"?{key}?";
        }

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

        private static T LoadLocalized<T>(string name) {
            var location = GameImpl.Instance.Content.RootDirectory + "/Localization/" + name;
            var culture = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
            foreach (var path in new[] {$"{location}.{culture}.json", $"{location}.json"}) {
                try {
                    using (var reader = new JsonTextReader(new StreamReader(TitleContainer.OpenStream(path))))
                        return SaveHandler.Serializer.Deserialize<T>(reader);
                } catch (Exception) {
                    // move on to the next path
                }
            }
            throw new ContentLoadException();
        }

    }
}