import 'dart:convert';
import 'dart:math';
import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:flutter/foundation.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/upgrade/app_version_info.dart';
import 'package:flyinsono/pages/upgrade/state.dart';
import 'package:flyinsono/pages/upgrade/upgrade_widgets/upgrade_center.dart';
import 'package:flyinsono/rpc.dart';
import 'package:package_info/package_info.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:http/http.dart' as http;

class UpgradeController {
  final state = UpgradeState();

  //对于非强制检查更新的场景，一旦设置为True后，就不会再次触发更新的检查
  bool updateConfirmed = false;

  bool _checkManually = false;
  Future<void> onInit(bool checkManually) async {
    _checkManually = checkManually;
    if (UpgradeCenter.notificationInfo != null) {
      _showUpdgradeWithNotification();
    } else {
      await _checkAppVersion();
    }
  }

  Future<void> _checkAppVersion() async {
    if (kDebugMode) {
      return;
    }
    if (FPlatform.isPureWeb) {
      var versionInfo = await rpc.upgrade.getFlyinsonoVersionAsync(
          new GetFlyinsonoVersionRequest(
              currentClientType: CurrentClientSourceTypeEnum.Web));
      UpgradeCenter.currentVersion = versionInfo;
      return;
    }
    var platform = UpgradePlatformEnum.PC;
    var currentVersion = "";
    if (FPlatform.isAndroid) {
      currentVersion = await _getVersionNumber();
      platform = UpgradePlatformEnum.Android;
    }
    if (FPlatform.isIOS) {
      currentVersion = await _getVersionNumber();
      platform = UpgradePlatformEnum.IOS;
    }
    if (FPlatform.isMacOS) {
      platform = UpgradePlatformEnum.Mac;
    }
    AppVersionInfo? versinInfo;
    if (currentVersion == "" && !FPlatform.isPureWeb) {
      var versinInfoStr = await rpc.platform.getCurrentAppVersion();
      var versionInfoJson = jsonDecode(versinInfoStr);
      versinInfo = AppVersionInfo.fromJson(versionInfoJson);
      currentVersion = versinInfo.flyinsonoVersion;
    }
    logger.i(
        "Current flyinsono version is:${versinInfo?.flyinsonoVersion ?? ''}");
    logger.i("Current shell version is:${versinInfo?.shellVersion ?? ''}");
    var isShell = FPlatform.isWindows || FPlatform.isMacOS;
    UpgradeCenter.currentVersion = currentVersion;
    UpgradeCenter.appVersionInfo = versinInfo;
    // if (FPlatform.isMacOS || FPlatform.isIOS) {
    //   return;
    // }
    if (Store.user.isLogin) {
      await rpc.upgrade.updateClientVersion(new SetUpgradeInfoRequest(
        platform: platform,
        sourceType: UpgradeSourceTypeEnum.Client,
        currentVersion: isShell
            ? UpgradeCenter.appVersionInfo!.versionInfoStr
            : UpgradeCenter.currentVersion,
        token: Store.user.token,
      ));
    }
    try {
      GetUpgradeInfoResult updateResult =
          await rpc.upgrade.getUpgradeInfoAsync(new GetUpgradeInfoRequest(
        platform: platform,
        sourceType: UpgradeSourceTypeEnum.Client,
        currentVersion: isShell
            ? UpgradeCenter.appVersionInfo!.versionInfoStr
            : UpgradeCenter.currentVersion,
        language:
            "${i18nBook.locale.languageCode}-${i18nBook.locale.countryCode}",
      ));
      print(jsonEncode(updateResult));
      UpgradeCenter.setUpgradeInfo(updateResult);
    } catch (e) {
      logger.e("getUpgradeInfoAsync fail");
    }
    await _setStateInfo();
  }

  Future<void> _setStateInfo() async {
    GetUpgradeInfoResult? updateResult = UpgradeCenter.getUpgradeResultInfo();
    if (updateResult == null) {
      return;
    }
    if (updateResult.upgradeType != UpgradeTypeEnum.NoUpgrade) {
      state.newVersion = updateResult.newVersion ?? "";
      state.contentTip = updateResult.description ?? "";
      state.downloadUrl =
          updateResult.upgradeCDNUrl ?? updateResult.upgradeSourceUrl ?? "";
      state.isForce = updateResult.upgradeType == UpgradeTypeEnum.Force;
      if (FPlatform.isIOS) {
        state.needUpdate = await _checkAppStoreForUpdate();
      } else {
        state.needUpdate = true;
      }
    } else {
      state.needUpdate = false;
      if (_checkManually) {
        PromptBox.toast(i18nBook.setting.latestVersionTip.t);
      }
    }
  }

  /// 检查App Store是否有更新
  Future<bool> _checkAppStoreForUpdate() async {
    try {
      final response = await http
          .post(Uri.parse('https://itunes.apple.com/lookup?id=1501133381'));
      if (response.statusCode == 200) {
        var jsonResponse = jsonDecode(response.body);
        var appStoreVersion = jsonResponse['results'][0]['version'];
        PackageInfo packageInfo = await PackageInfo.fromPlatform();
        String currentVersion = packageInfo.version;

        /// 此处读 packageInfo.version 而不是 packageInfo.buildNumber
        /// 因为 appstore 上只能取到前三位大版本号比如 2.0.9，而 buildNumber 是 2.0.9.4393
        if (appStoreVersion != currentVersion) {
          logger.i(
              "App Store Check Update available! App Store version: $appStoreVersion, Current version: $currentVersion");
          print(
              '✨✨✨✨✨ Update available! App Store version: $appStoreVersion, Current version: $currentVersion');
          return true;
        } else {
          logger.i(
              "App Store Check No Update available! App Store version: $appStoreVersion, Current version: $currentVersion");
          print('✨✨✨✨✨ No update available.');
          return false;
        }
      }
    } catch (e) {
      return true;
    }
    return true;
  }

  Future<String> _getVersionNumber() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version =
        FPlatform.isIOS ? "${packageInfo.buildNumber}" : packageInfo.version;
    logger.i("Version Number Current version is:$version");
    return version;
  }

  void _showUpdgradeWithNotification() async {
    UpgradeCenter.setUpgradeInfoWithNotification();
    await _setStateInfo();
  }
}
