import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/widgets.dart';
import 'package:flyinsono/architecture/config/config.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/main/home/widgets/dialog_page.dart';
import 'package:flyinsono/pages/upgrade/upgrade_controller.dart';
import 'package:flyinsono/pages/upgrade/upgrade_widgets/app_upgrade.dart';
import 'package:flyinsono/pages/upgrade/upgrade_widgets/upgrade_center.dart';
import 'package:get/get.dart';
import 'package:fis_common/logger/logger.dart';

///升级界面包装
class UpgradeWrapper {
  static String _iosAppId = "id88888888";

  //升级Manager
  static UpgradeController? upgradeController;

  /// 配置
  static ConfigService get config => ConfigService.ins;

  static Future<void> initUpgrade(bool checkManually) async {
    await upgradeController!.onInit(checkManually);
  }

  static Future<void> invokeUpgradeDirectly(
    BuildContext context,
    bool forceCheckUpgrade, {
    bool checkManually = false, // 页面上手动触发
  }) async {
    logger.i('invokeUpgradeDirectly start');
    if (UpgradeCenter.isChecking) {
      logger.i('invokeUpgradeDirectly is checking');
      return;
    } else {
      UpgradeCenter.isChecking = true;
    }
    try {
      if (upgradeController == null) {
        logger.i('invokeUpgradeDirectly create upgrade controller');
        upgradeController = new UpgradeController();
      }
      //如果已进行过强制检测更新，且当前检测不是强制检测的情况下，则不检测更新
      if (upgradeController!.updateConfirmed && !forceCheckUpgrade) {
        print(
            "Upgrade confirmed ${upgradeController!.updateConfirmed}, force check upgrade $forceCheckUpgrade");
        UpgradeCenter.isChecking = false;
        logger.i('invokeUpgradeDirectly non-force checking returned ');
        return;
      }
      await initUpgrade(checkManually);
      if (upgradeController!.state.needUpdate) {
        logger.i('invokeUpgradeDirectly show upgrade dialog');
        print("Show upgrade dialog");
        AppUpgrade.appUpgrade(
          okText: i18nBook.setting.upgradeNow.t,
          cancelText: i18nBook.setting.upgradeLater.t,
          context,
          _checkAppInfo(
            upgradeController!.state.isForce,
            upgradeController!.state.downloadUrl,
            upgradeController!.state.newVersion,
            upgradeController!.state.contentTip,
          ),
          iosAppId: _iosAppId,
          onOk: () {
            UpgradeCenter.isChecking = false;
            UpgradeCenter.notificationInfo = null;
            upgradeController!.updateConfirmed = true;
          },
          onCancel: () {
            print("Upgrade dialog cancelled");
            UpgradeCenter.isChecking = false;
            UpgradeCenter.notificationInfo = null;
            upgradeController!.updateConfirmed = true;
            try {
              Get.find<FWebviewInteractiveController>().onDialogDispose();
            } catch (e) {
              print(e);
            }
          },
        );
      } else {
        logger.i('invokeUpgradeDirectly no need to update');
        if (checkManually) {
          PromptBox.toast(i18nBook.setting.latestVersionTip.t);
        }
        UpgradeCenter.isChecking = false;
      }
    } catch (e) {
      if (checkManually && _isNetworkError(e)) {
        PromptBox.toast(i18nBook.common.networkError.t);
      }
      UpgradeCenter.isChecking = false;
    }
  }

  static void cancelUpdateOnDispose() {
    // 离开页面时取消检测
    UpgradeCenter.isChecking = false;
  }

  static Future<AppUpgradeInfo> _checkAppInfo(
      bool isForce, String downloadUrl, String title, String contents) async {
    return Future.delayed(Duration(seconds: 1), () {
      return AppUpgradeInfo(
        force: isForce,
        apkDownloadUrl: downloadUrl,
        title: '${i18nBook.setting.newVersion.t} $title',
        contents: [contents],
      );
    });
  }

  static bool _isNetworkError(e) {
    return e is JsonRpcNetworkException &&
        e.message != null &&
        e.message!.contains("Network is unreachable");
  }
}
