import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:vitalapp/managers/interfaces/account.dart';
import 'package:vitalapp/managers/interfaces/models/upgrade.dart';
import 'package:vitalapp/managers/interfaces/permission.dart';
import 'package:vitalapp/managers/interfaces/upgrade.dart';
import 'package:vitalapp/pages/settings/center/state.dart';
import 'package:vitalapp/store/store.dart';

class SettingCenterController extends GetxController {
  final state = SettingCenterState();
  @override
  void onInit() async {
    state.currentVersion = await getCurrentVersion();
    super.onInit();
  }

  /// 登出
  Future<void> logOut() async {
    final result = await Get.find<IAccountManager>().logout();
    if (result) {
      Store.user.currentSelectPatientInfo = null;
      Get.offAllNamed("/login");
    }
  }

  Future<UpgradeCheckResultModel?> checkNewVersionArrival() async {
    final result = await Get.find<IUpgradeManager>().checkNewVersionArrival();
    return result;
  }

  Future<bool> downloadPackage(
    String version,
    String url, {
    ValueChanged<double>? onProgress,
  }) async {
    final result = await Get.find<IUpgradeManager>()
        .downloadPackage(version, url, onProgress: onProgress);
    return result;
  }

  Future<void> installPackage(String version) async {
    var permissionManager = Get.find<IPermissionManager>();
    await permissionManager.requestInstallPackagesPermission();
    await Get.find<IUpgradeManager>().install(version);
  }

  ///获取当前版本号
  Future<String> getCurrentVersion() async {
    var version = await Get.find<IUpgradeManager>().getCurrentVersion();
    return version;
  }
}
