import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:get/get.dart';

///APP主题
class AppTheme extends FTheme {
  static AppTheme get ins => Get.find();

  AppTheme(
      {String defaultName = "lightness",
      ThemeMode themeMode = ThemeMode.system})
      : super(defaultName: defaultName, themeMode: themeMode);

  @override
  bool get isCurrentChinese => Get.find<FI18n>().isCurrentChinese;

  @override
  Future<void> reload() async {
    BuildContext? context = Get.context;
    if (context != null) EasyLoading.show(maskType: EasyLoadingMaskType.black);
    try {
      await super.reload();
      Get.changeTheme(this.innerThemeData);
    } catch (e) {
      logger.e("Theme load failed", e);
    } finally {
      EasyLoading.dismiss();
    }
  }

  @override
  Future<bool> switchTheme([String? name]) async {
    BuildContext? context = Get.context;
    if (context != null) EasyLoading.show(maskType: EasyLoadingMaskType.black);
    try {
      bool loaded = await super.switchTheme(name);
      if (!loaded) {
        PromptBox.toast(i18nBook.auth.switchFailed.t);
      }
      return loaded;
    } catch (e) {
      logger.e("Theme: [$name] change failed", e);
    } finally {
      EasyLoading.dismiss();
    }
    return false;
  }

  @override
  Future<void> buildInnerThemeData() async {
    // 中英文字体同时载入，防止英文模式下默认英文字体不支持单独显示的中文
    await FFontLoader.load(
      this.data.localeSettings.chinese.fontFamily,
      FResourceKey(this.data.localeSettings.chinese.fontFamilySource),
    );
    await FFontLoader.load(
      this.data.localeSettings.english.fontFamily,
      FResourceKey(this.data.localeSettings.english.fontFamilySource),
    );
    return super.buildInnerThemeData();
  }

  @override
  void applyThemeData() {
    final lightData = getInnerThemeData(Brightness.light);
    final darkData = getInnerThemeData(Brightness.dark);

    // 手动设置数据&触发更新
    Get.changeTheme(
        currentBrightness == Brightness.dark ? darkData : lightData);
  }

  @override
  Brightness get currentBrightness {
    final context = Get.context;
    if (context == null) return Brightness.light;
    return MediaQuery.platformBrightnessOf(context);
  }

  @override
  Future<void> switchThemeMode(ThemeMode mode) async {
    await super.switchThemeMode(mode);
    Get.changeThemeMode(mode);
    // final localeSetting = this.isCurrentChinese
    //     ? this.data.localeSettings.chinese
    //     : this.data.localeSettings.english;
    // GetNavigation.getxController.darkTheme?.textTheme
    //     .apply(fontFamily: localeSetting.fontFamily);
  }
}
