import 'package:fis_common/event/event_type.dart';
import 'package:fis_common/index.dart';
import 'package:fis_ui/index.dart';
import 'package:flyinsono/pages/main/home/widgets/dialog_page.dart';
import 'package:flyinsono/pages/upgrade/upgrade_widgets/upgrade_center.dart';
import 'package:get/get.dart';
import 'package:webviewx/webviewx.dart';
import 'package:fis_common/logger/logger.dart';
import 'interfaces/webview_controller.dart';

class WebviewControllerManager implements IWebviewControllerManager {
  WebViewXController? webViewXController;
  FEventHandler<bool> onInit = FEventHandler<bool>();
  FWebviewInteractiveController? webviewInteractiveController;
  bool get isDialogExist => webviewInteractiveController == null
      ? false
      : webviewInteractiveController?.isDialogExist ?? false;

  ///初始化webview控制器
  @override
  void initWebviewController(WebViewXController webViewXController) {
    if (kIsMobile) return;
    Future.delayed(Duration(milliseconds: 200), () {
      this.webViewXController = webViewXController;
      webviewInteractiveController = Get.find<FWebviewInteractiveController>();
      webviewInteractiveController?.onDialogExistStatusChanged
          .addListener(_onDialogExistStateChanged);
      if (UpgradeCenter.isChecking) {
        logger.i("OndialogCreate since is checking");
        webviewInteractiveController?.onDialogCreate();
      }
      onInit.emit(this, true);
    });
  }

  ///销毁webview控制器
  @override
  void disposeWebviewController() {
    if (kIsMobile) return;
    webViewXController = null;
    webviewInteractiveController?.onDialogExistStatusChanged
        .removeListener(_onDialogExistStateChanged);
  }

  //禁用or开始webview交互
  void _onDialogExistStateChanged(e, bool exist) {
    if (FPlatform.isPureWeb || FPlatform.isWindows || FPlatform.isMacOS) {
      print("Last webview controller status $exist");
      if (webViewXController == null) {
        print("Webview controller is null while setting something");
      }
      webViewXController?.setIgnoreAllGestures(exist);
    }
  }
}
