import 'package:flutter/foundation.dart';
import 'package:flyinsono/architecture/services/entity/local_setting.dart';
import 'package:flyinsono/architecture/services/modules/local_setting_configurations.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/js_platform/methods.dart';
import 'package:flyinsono/managers/interfaces/window_state_manager.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:fis_i18n/i18n.dart';
import 'base.dart';

class OpenSecondWindowLoading extends MethodHandlerBase {
  OpenSecondWindowLoading() : super(TargetMethodName.OpenSecondWindowLoading);
  int? _targetMethodInt;
  String? _content;

  ///本地配置缓存服务
  final localSettingService = Get.find<LocalSettingService>();
  final windowStateManager = Get.find<IWindowStateManager>();
  @override
  void execute(List<String> args) {
    _targetMethodInt = int.parse(args[0]);
    _content = args[1];

    windowStateManager.onSecondWindowChange.addListener(_onSecondWindowChange);

    Store.app.setBusy(i18nBook.common.openSecondaryWindow.t);
    Future.delayed(Duration(seconds: kDebugMode ? 100 : 60), () {
      Store.app.cancelBusy();
      windowStateManager.onSecondWindowChange
          .removeListener(_onSecondWindowChange);
      _targetMethodInt = null;
    });
  }

  void _onSecondWindowChange(Object sender, bool e) {
    if (e) {
      Store.app.cancelBusy();
      PromptBox.toast(i18nBook.setting.switchingSecondWindowSuccess.t);
      LocalSetting.ins.isUseSecondWindow = true;
      localSettingService.save();
      if (_targetMethodInt != null) {
        rpc.platform.continueExcute(_targetMethodInt!, _content ?? '');
      }
    }
  }
}
