import 'dart:convert';

import 'package:fis_common/event/event_type.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/notifications/handlers/upgrade/upgrade_notification.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:flyinsono/pages/main/home/widgets/dialog_page.dart';
import 'package:flyinsono/pages/upgrade/app_version_info.dart';
import 'package:flyinsono/pages/upgrade/upgrade_widgets/updrade_warpped_dialog.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:fis_common/env/env.dart';
import 'package:fis_common/logger/logger.dart';

///系统更新中心
class UpgradeCenter {
  ///更新结果信息
  static GetUpgradeInfoResult? _upgradeResultInfo;

  /// 下载进度事件
  static FEventHandler<String> onDownloadProgressChanged =
      FEventHandler<String>();

  /// 更新通知事件
  static FEventHandler<UpgradeNotification> onUpgradeInvoked =
      FEventHandler<UpgradeNotification>();

  //设置更新信息
  static setUpgradeInfo(GetUpgradeInfoResult result) {
    _upgradeResultInfo = result;
  }

  ///获得更新结果信息
  static GetUpgradeInfoResult? getUpgradeResultInfo() {
    return _upgradeResultInfo;
  }

  //根据通知设置更新信息
  static setUpgradeInfoWithNotification() {
    if (notificationInfo != null) {
      _upgradeResultInfo = new GetUpgradeInfoResult(
        upgradeType: notificationInfo!.upgadeType,
        upgradeCDNUrl: notificationInfo!.upgradeCDNUrl,
        upgradeSourceUrl: notificationInfo!.upgradeUrl,
        upgradeUpdateType: notificationInfo!.upgradeUpdateType,
        description: notificationInfo!.description,
        newVersion: notificationInfo!.newVersion,
      );
    }
  }

  //获得json编码的更新结果信息
  static String getResultInfoStr() {
    return jsonEncode(_upgradeResultInfo);
  }

  //正在升级中
  static bool isBusy = false;

  //正在弹框显示中
  static bool isChecking = false;

  //当前软件版本
  static String currentVersion = "2.0.0";

  static Future<String> getCurrentFISVersion() async {
    try {
      if (currentVersion == "2.0.0" &&
          (FPlatform.isWindows || FPlatform.isMacOS)) {
        var versinInfoStr = await rpc.platform.getCurrentAppVersion();
        var versionInfoJson = jsonDecode(versinInfoStr);
        var versinInfo = AppVersionInfo.fromJson(versionInfoJson);
        currentVersion = versinInfo.flyinsonoVersion;
        logger.i(
            "Current version is set correctly, version value is:$currentVersion");
      }
      return currentVersion;
    } catch (e) {
      logger.e("Error happened while get version data $e");
      return "2.0.Default";
    }
  }

  ///当前版本信息
  static AppVersionInfo? appVersionInfo;

  static UpgradeNotification? notificationInfo;

  ///接收下载进度
  static void emitProgressChanged(String progress) {
    onDownloadProgressChanged.emit(progress, progress);
  }

  static init() {
    var upgradeNotification = Get.find<UpgradeNotificationHandler>();
    upgradeNotification.subscribe((upgradeNotification) {
      if (UpgradeCenter.isChecking) {
        return;
      }
      try {
        Get.find<FWebviewInteractiveController>().onDialogCreate();
      } catch (e) {
        print("Error happened while on dialog created");
        print(e);
      }
      notificationInfo = upgradeNotification;
      router.dialog(
        () => UpgradeWrappedDialog(
          forceCheckUpgrade: true,
        ),
        isShowBarrier: false,
      );
      onUpgradeInvoked.emit(upgradeNotification, upgradeNotification);
    });
  }
}
