|
| 1 | +// Copyright (c) Alamo Engine Tools and contributors. All rights reserved. |
| 2 | +// Licensed under the MIT license. See LICENSE file in the project root for details. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Linq; |
| 6 | +using System.Reflection; |
| 7 | +using PG.Commons.Services; |
| 8 | +using PG.StarWarsGame.Components.Localisation.Attributes; |
| 9 | +using PG.StarWarsGame.Components.Localisation.Exceptions; |
| 10 | +using PG.StarWarsGame.Components.Localisation.Languages; |
| 11 | + |
| 12 | +namespace PG.StarWarsGame.Components.Localisation.Services; |
| 13 | + |
| 14 | +/// <inheritdoc cref="PG.StarWarsGame.Components.Localisation.Services.IAlamoLanguageSupportService" /> |
| 15 | +public class AlamoLanguageSupportService : ServiceBase, IAlamoLanguageSupportService |
| 16 | +{ |
| 17 | + private IAlamoLanguageDefinition _fallbackAlamoLanguageDefinition; |
| 18 | + |
| 19 | + /// <inheritdoc /> |
| 20 | + public AlamoLanguageSupportService(IServiceProvider services) : base(services) |
| 21 | + { |
| 22 | + _fallbackAlamoLanguageDefinition = GetDefaultLanguageDefinition(); |
| 23 | + } |
| 24 | + |
| 25 | + /// <inheritdoc /> |
| 26 | + public bool IsBuiltInLanguageDefinition(IAlamoLanguageDefinition definition) |
| 27 | + { |
| 28 | + return definition.GetType().GetCustomAttribute(typeof(OfficiallySupportedLanguageAttribute)) != null; |
| 29 | + } |
| 30 | + |
| 31 | + /// <inheritdoc /> |
| 32 | + public IAlamoLanguageDefinition GetFallBackLanguageDefinition() |
| 33 | + { |
| 34 | + return _fallbackAlamoLanguageDefinition; |
| 35 | + } |
| 36 | + |
| 37 | + /// <inheritdoc /> |
| 38 | + public IAlamoLanguageSupportService WithOverrideFallbackLanguage(IAlamoLanguageDefinition definition) |
| 39 | + { |
| 40 | + _fallbackAlamoLanguageDefinition = definition; |
| 41 | + return this; |
| 42 | + } |
| 43 | + |
| 44 | + /// <inheritdoc /> |
| 45 | + public IAlamoLanguageDefinition GetDefaultLanguageDefinition() |
| 46 | + { |
| 47 | + var languageDefinitions = AppDomain.CurrentDomain.GetAssemblies() |
| 48 | + .SelectMany(assemblyTypes => assemblyTypes.GetTypes()) |
| 49 | + .Where(assemblyType => typeof(IAlamoLanguageDefinition).IsAssignableFrom(assemblyType) && |
| 50 | + assemblyType is { IsClass: true, IsAbstract: false }) |
| 51 | + .Where(t => t.GetCustomAttribute(typeof(DefaultLanguageAttribute)) != null) |
| 52 | + .ToList(); |
| 53 | + if (languageDefinitions.Count != 1) |
| 54 | + throw new InvalidDefaultLanguageDefinitionException(languageDefinitions.Count > 1 |
| 55 | + ? "Multiple default languages have been defined." |
| 56 | + : "No default language has been defined."); |
| 57 | + return (IAlamoLanguageDefinition)Activator.CreateInstance(languageDefinitions[0]); |
| 58 | + } |
| 59 | +} |
0 commit comments