import 'package:flutter/material.dart';
import 'strings/zh_cn.dart';
import 'strings/zh_tw.dart';
import 'strings/en.dart';
import 'strings/ja.dart';

/// Genex 多语言支持
///
/// 使用方式: context.t('key') 或 AppLocalizations.of(context).get('key')
/// 支持语言: zh_CN(默认), zh_TW, en, ja
class AppLocalizations {
  final Locale locale;
  late final Map<String, String> _strings;

  AppLocalizations(this.locale) {
    final key = locale.countryCode != null && locale.countryCode!.isNotEmpty
        ? '${locale.languageCode}_${locale.countryCode}'
        : locale.languageCode;

    _strings = _allStrings[key] ?? _allStrings[locale.languageCode] ?? zhCN;
  }

  static AppLocalizations of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations)!;
  }

  /// 获取翻译字符串，找不到时 fallback 到中文，再找不到返回 key
  String get(String key) => _strings[key] ?? zhCN[key] ?? key;

  static const Map<String, Map<String, String>> _allStrings = {
    'zh': zhCN,
    'zh_CN': zhCN,
    'zh_TW': zhTW,
    'en': en,
    'ja': ja,
  };
}

/// LocalizationsDelegate
class AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
  const AppLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) {
    return ['zh', 'en', 'ja'].contains(locale.languageCode);
  }

  @override
  Future<AppLocalizations> load(Locale locale) async {
    return AppLocalizations(locale);
  }

  @override
  bool shouldReload(covariant LocalizationsDelegate<AppLocalizations> old) =>
      false;
}

/// BuildContext 扩展，快捷访问翻译
extension AppLocalizationsExtension on BuildContext {
  /// 快捷翻译: context.t('key')
  String t(String key) => AppLocalizations.of(this).get(key);
}
