TouchyTickets/TouchyTickets/Localization.cs

50 lines
2 KiB
C#
Raw Normal View History

2020-06-02 14:16:14 +02:00
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Microsoft.Xna.Framework;
2020-06-04 21:43:11 +02:00
using Microsoft.Xna.Framework.Content;
2020-06-02 14:16:14 +02:00
using MLEM.Startup;
using Newtonsoft.Json;
namespace TouchyTickets {
public static class Localization {
2020-06-25 14:18:57 +02:00
public static readonly List<string> NumberFormat = LoadLocalized<List<string>>("NumberFormat", "json5");
2020-06-04 21:43:11 +02:00
private static readonly Dictionary<string, string> Strings = LoadLocalized<Dictionary<string, string>>("Localization");
private static readonly Dictionary<string, string> FallbackStrings = Load<Dictionary<string, string>>("Localization");
2020-06-04 21:43:11 +02:00
private static readonly List<string> News = LoadLocalized<List<string>>("News");
private static readonly Random Random = new Random();
2020-06-02 14:16:14 +02:00
2020-06-04 21:43:11 +02:00
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}?";
2020-06-04 21:43:11 +02:00
}
public static string GetRandomNews() {
return News[Random.Next(News.Count)];
}
2020-06-25 14:18:57 +02:00
private static T LoadLocalized<T>(string name, string extension = "json") {
2020-06-02 14:16:14 +02:00
var culture = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
foreach (var path in new[] {$"{name}.{culture}", name}) {
2020-06-02 14:16:14 +02:00
try {
return Load<T>(path, extension);
2020-06-02 14:16:14 +02:00
} catch (Exception) {
// move on to the next path
}
}
2020-06-04 21:43:11 +02:00
throw new ContentLoadException();
2020-06-02 14:16:14 +02:00
}
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);
}
2020-06-02 14:16:14 +02:00
}
}