import 'package:fis_common/event/event_type.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:get/get.dart';
import 'package:fis_common/logger/logger.dart';

/// webview 交互控制器
///
/// 控制 webview 交互是否可用
class FWebviewInteractiveController extends GetxController {
  /// 弹窗状态事件通知
  FEventHandler<bool> onDialogExistStatusChanged = FEventHandler<bool>();

  bool get isDialogExist => _dialogCount > 0;

  /// 弹窗计数器
  int _dialogCount = 0;

  /// 创建弹窗，禁用 Webview 交互
  void onDialogCreate() {
    _dialogCount++;

    onDialogExistStatusChanged.emit(this, true);
  }

  /// 销毁弹窗，如果不存在弹窗，启用 Webview 交互
  void onDialogDispose() {
    _dialogCount--;
    if (_dialogCount <= 0) {
      _dialogCount = 0;
      logger.i(
          "Dialog exist status changing invoked to be false, since exist dialog count is zero");
      onDialogExistStatusChanged.emit(this, false);
    } else {
      logger.i("Dialog count is $_dialogCount, so don't set webview");
    }
  }

  void forceOperationGesture() {}
}

abstract class FisOverlayView<T> extends FisView<T> implements FWidget {
  const FisOverlayView({Key? key}) : super(key: key);
  @override
  FWidget build(BuildContext context);
}

/// 弹窗容器
///
/// 创建时会禁用 Webview 交互
///
/// 销毁时会启用 Webview 交互
class FOverlayContainer extends FisOverlayView<OverlayViewController> {
  const FOverlayContainer({Key? key, required this.child}) : super(key: key);
  final FWidget child;

  @override
  FWidget build(BuildContext context) {
    return child;
  }
}

/// 弹窗控制器，当 webview 交互控制器存在时，改变 webview 可交互状态
class OverlayViewController extends GetxController {
  @override
  void onInit() {
    super.onInit();
    try {
      Get.find<FWebviewInteractiveController>().onDialogCreate();
    } catch (e) {
      print(e);
    }
  }

  @override
  void onClose() {
    super.onClose();
    try {
      Get.find<FWebviewInteractiveController>().onDialogDispose();
    } catch (e) {
      print(e);
    }
  }
}
