using System.Globalization;
using System.Resources;
using Titano.Core.Localization;
namespace Titano.App.Settings;
/// A language of the language pickers: culture code and its own name ("Italiano").
public sealed record LanguageOption(string Code, string Name);
///
/// The languages this build ships (BRIEF ยง16): English plus every language of whose
/// resources are compiled in. Languages announced for later phases appear as soon as their resources exist, and
/// never before (a picker entry that shows English text would mislead).
///
public static class LanguageCatalog
{
private static readonly Lazy> Detected = new(Detect);
/// Available languages, English first, then by native name.
public static IReadOnlyList Available => Detected.Value;
/// True when the satellite resources of exist.
public static bool HasResources(string code)
{
if (code.Equals("en", StringComparison.OrdinalIgnoreCase)) return true;
var manager = new ResourceManager("Titano.Core.i18n.Common", typeof(Loc).Assembly);
try
{
return manager.GetResourceSet(CultureInfo.GetCultureInfo(code), createIfNotExists: true, tryParents: false) is not null;
}
catch (MissingManifestResourceException)
{
return false;
}
catch (CultureNotFoundException)
{
return false;
}
}
/// The option matching (or its parent), English when none does.
public static LanguageOption Match(CultureInfo culture)
{
for (var c = culture; !Equals(c, CultureInfo.InvariantCulture); c = c.Parent)
{
var hit = Available.FirstOrDefault(o => o.Code.Equals(c.Name, StringComparison.OrdinalIgnoreCase));
if (hit is not null) return hit;
}
return Available[0];
}
private static IReadOnlyList Detect()
{
var found = Languages.Shipped
.Where(code => !code.Equals("en", StringComparison.OrdinalIgnoreCase) && HasResources(code))
.Select(code => new LanguageOption(code, Languages.NativeName(code)))
.OrderBy(o => o.Name, StringComparer.CurrentCultureIgnoreCase)
.ToList();
found.Insert(0, new LanguageOption("en", Languages.NativeName("en")));
return found;
}
}