import 'package:guru_utils/log/log.dart';

/// Created by Haoyi on 2022/8/15

// enum HookScene { watchRewardAds, audit }

class HookScene {
  final String name;

  const HookScene.define(this.name);

  static const watchRewardAds = HookScene.define("watchRewardAds");
}

typedef HookCallback = void Function(dynamic);

class HookManager {
  final Map<HookScene, List<HookCallback>> hooks = {};

  HookManager._();

  static final HookManager instance = HookManager._();

  void addHook(HookScene scene, HookCallback callback) {
    List<HookCallback>? callbacks = hooks[scene];
    if (callbacks == null) {
      callbacks = <HookCallback>[];
      hooks[scene] = callbacks;
    } else {
      callbacks.remove(callback);
    }
    callbacks.add(callback);
  }

  void removeHook(HookScene scene, HookCallback callback) {
    List<HookCallback>? callbacks = hooks[scene];
    if (callbacks != null) {
      callbacks.remove(callback);
    }
  }

  void dispatch(HookScene scene, dynamic params) {
    final callbacks = hooks[scene]?.toList() ?? [];
    for (var callback in callbacks) {
      try {
        callback(params);
      } catch (error, stacktrace) {
        Log.w("_dispatch hook[$scene] params:$params error! $error!", stackTrace: stacktrace);
      }
    }
  }

  void watchRewardAds() {
    dispatch(HookScene.watchRewardAds, null);
  }
}
