/// Created by Haoyi on 2020/4/16
///
///
part of "router.dart";

class RouteCenter {
  static final RouteCenter instance = RouteCenter._();

  final List<RouteMatcher> _matchers = [];

  RouteCenter._();

  static void initialize({List<RouteMatcher> routeMatchers = const []}) {
    instance._matchers.addAll(routeMatchers);
  }

  static Map<String, List<String>> convertQueryParamsToRouteParams(Map<String, String> params) {
    return Map.fromEntries(
        params.entries.map((entry) => MapEntry(entry.key, [entry.value])).toList());
  }

  Future<Object?> dispatchUri(Uri uri) {
    return openUri(uri);
  }

  Future openUri(Uri uri) {
    Log.d("openUri: $uri ${uri.path}");
    for (var matcher in _matchers) {
      if (matcher.checker(uri)) {
        return matcher.dispatcher(uri);
      }
    }
    FeedbackManager.instance.perform(FeedbackOccasion.openPage);
    return Get.toNamed(uri.toString()) ?? Future.value();
  }

  Future openPath(String path) {
    FeedbackManager.instance.perform(FeedbackOccasion.openPage);
    return Get.toNamed(path) ?? Future.value();
  }

  bool canPop() {
    return Get.global(null).currentState?.canPop() == true;
  }

  void back({dynamic result, AudioEffect? audio}) {
    if (canPop()) {
      if (audio != null) {
        AudioEffector.instance.play(audio);
      } else {
        FeedbackManager.instance.perform(FeedbackOccasion.backPage);
      }
      Get.back(result: result);
    }
  }

  void until({dynamic result, AudioEffect? audio, RoutePredicate? predicate}) {
    if (canPop()) {
      if (audio != null) {
        AudioEffector.instance.play(audio);
      } else {
        FeedbackManager.instance.perform(FeedbackOccasion.backPage);
      }
      Get.until(predicate ??
          (route) {
            return (Get.isDialogOpen == false) && Get.currentRoute == '/';
          });
    }
  }
}
