import 'package:webviewx/webviewx.dart';

class WebviewXDartAsyncCallback implements DartCallback {
  static const _name = "Dart_AsyncCall";

  final WebViewXController? Function() controllerGetter;

  final Map<String, Future<dynamic> Function(dynamic data)>? methods;

  WebviewXDartAsyncCallback({
    required this.controllerGetter,
    this.methods,
  });

  dynamic _handle(dynamic message) async {
    final controller = controllerGetter();
    if (controller == null) return;
    if (methods == null) return;

    final methodName = message['method'];
    if (methods!.containsKey(methodName) == false) return;

    final method = methods![methodName]!;

    final requestId = message['rid'];
    final data = message['data'];
    dynamic result = await method.call(data);
    controller.callJsMethod("dartCallback", [requestId, result]);
  }

  @override
  Function(dynamic message) get callBack => _handle;

  @override
  String get name => _name;
}
