import 'package:flyinsono/lab/manager/page_manager.dart';
import 'package:get/get.dart';

/// Tab 页扩展功能，用于控制 tab 页的激活和休眠
///
/// 使用方法，初始化控制器时候传入 controller 所在 page 的 hashId
///
/// e.g.
/// ```dart
/// class LabTaskController extends GetxController with TabHookMixin {
///  LabTaskController({required this.tabHashCode});
///
///  @override
///  int tabHashCode;
///   ....
/// }
/// ```
/// page 初始化时候传入 hashId
/// ```dart
/// class LabTaskPage extends GetView<LabTaskController> {
/// const LabTaskPage({Key? key}) : super(key: key);
///
/// @override
/// Widget build(BuildContext context) {
///   return GetBuilder<LabTaskController>(
///     init: LabTaskController(tabHashCode: this.hashCode),
/// .....
/// ```
mixin TabHookMixin on GetxController {
  /// 一般情况下传入当前页面的 hashCode (this.hashCode)
  int get tabHashCode;

  bool isTabActive = true;

  /// tab 页休眠时候调用
  void onSleep();

  /// tab 页激活时候调用（首次进入不调用）
  void onActive(dynamic arguments);

  void initTabStateListener() {
    // 此处检查 tabHashCode 是否初始化
    try {
      final int temp = tabHashCode;
      print("TabHookMixin init tabHashCode: $temp");
    } catch (e) {
      Get.log("tabHashCode 未初始化，请根据使用方法先初始化 tabHashCode");
      return;
    }
    try {
      PageManager.ins.tabChangeEvent.addListener(tabChangeHandler);
      isTabActive = PageManager.ins.activeTabHash == tabHashCode;
    } catch (e) {
      print("TabHookMixin init failed: $e");
    }
  }

  void removeTabStateListener() {
    try {
      PageManager.ins.tabChangeEvent.removeListener(tabChangeHandler);
    } catch (e) {
      print("TabHookMixin remove failed: $e");
    }
  }

  void tabChangeHandler(_, TabChangeRequest request) {
    try {
      if (tabHashCode == request.tabHash) {
        if (!isTabActive) {
          Get.log(
              'GetxController instance with tag "$tabHashCode" now is active.');
          onActive(request.arguments);
          isTabActive = true;
        }
      } else {
        if (isTabActive) {
          Get.log(
              'GetxController instance with tag "$tabHashCode" now goes to sleep');
          onSleep();
          isTabActive = false;
        }
      }
    } catch (e) {
      print("tabChangeHandler failed: $e");
    }
  }

  @override
  void onInit() {
    super.onInit();
    initTabStateListener();
  }

  @override
  void onReady() {
    super.onReady();
    if (isTabActive) {
      Get.log('GetxController instance with tag "$tabHashCode" now is active.');
    }
  }

  @override
  void onClose() {
    super.onClose();
    removeTabStateListener();
  }

  @override
  void dispose() {
    super.dispose();
    removeTabStateListener();
  }
}
