BITKit/Src/Unity/Scripts/UX/Localization/UXLocalization.cs

74 lines
2.4 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BITKit;
using BITKit.UX;
using Net.BITKit.Localization;
using UnityEngine;
using UnityEngine.UIElements;
namespace Net.BITKit.UX
{
public class UXLocalization
{
public string USS { get; set; } = "localized";
private readonly IUXService _uxService;
private readonly ILocalizationService _localizationService;
public UXLocalization(IUXService uxService, ILocalizationService localizationService)
{
_uxService = uxService;
_localizationService = localizationService;
_localizationService.OnLanguageChanged += OnLanguageChanged;
}
private void OnLanguageChanged(string arg1, string arg2)
{
if(_uxService.Root is not VisualElement visualElement)return;
foreach (var x in visualElement.Query<Label>(className:USS).ToList())
{
if (string.IsNullOrEmpty(x.viewDataKey))continue;
x.text = _localizationService.GetLocalizedString('#'+x.viewDataKey);
}
foreach (var x in visualElement.Query<Button>(className:USS).ToList())
{
if(string.IsNullOrEmpty(x.viewDataKey))continue;
x.text = _localizationService.GetLocalizedString('#'+x.viewDataKey);
}
foreach (var x in visualElement.Query(className:USS).ToList())
{
if(string.IsNullOrEmpty(x.viewDataKey))continue;
ContinueWithBaseType(x.GetType());
continue;
void ContinueWithBaseType(Type type)
{
while (true)
{
if (type == null || type == typeof(object)) return;
if (type.GetProperty("label", ReflectionHelper.Flags) is { } propertyInfo)
{
//Debug.Log($"{x.name}:#{x.viewDataKey}");
propertyInfo.SetValue(x, _localizationService.GetLocalizedString('#' + x.viewDataKey));
}
else
{
type = type.BaseType;
continue;
}
break;
}
}
}
}
}
}