import 'package:firebase_dynamic_links/firebase_dynamic_links.dart';
import 'package:flutter/services.dart';
import 'package:guru_app/guru_app.dart';
import 'package:guru_navigator/guru_navigator.dart';
import 'package:guru_utils/log/log.dart';
import 'package:guru_utils/router/router.dart';
import 'package:guru_utils/uri/uri_utils.dart';

/// Created by Haoyi on 5/20/21

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

  DxLinkManager._();

  void initDynamicLinks() async {
    FirebaseDynamicLinks.instance.onLink.listen((PendingDynamicLinkData? dynamicLink) async {
      final Uri? deepLink = dynamicLink?.link;
      Log.d("### onDynamicLink $deepLink");
      if (deepLink != null) {
        _openLink(deepLink);
      }
    }, onError: (e) async {
      Log.w('onLinkError ${e.message} ${e.stacktrace}', error: e);
    });

    final PendingDynamicLinkData? data =
        await FirebaseDynamicLinks.instance.getInitialLink().catchError((error, stacktrace) {
      Log.d("getInitialLink error:$error $stacktrace");
    });
    final Uri? deepLink = data?.link;
    Log.d("initDynamicLinks: $deepLink");
    if (deepLink != null) {
      Future.delayed(const Duration(seconds: 2), () => _openLink(deepLink));
    }
  }

  Future<dynamic> _handleDeeplink(MethodCall call) async {
    Log.d("call.method: ${call.method} arguments:${call.arguments}");
    switch (call.method) {
      case "navigate":
        final uri = Uri.parse(call.arguments["uri"]);
        if ((uri.authority.isNotEmpty != true) ||
            uri.toString().contains(GuruApp.instance.appSpec.details.authority)) {
          _openLink(uri);
        } else {
          UriUtils.launchURL(uri);
        }
    }
    return true;
  }

  void initDeeplink() async {
    GuruNavigator.init(_handleDeeplink);
  }

  void init() async {
    initDeeplink();
    initDynamicLinks();
  }

  void _openLink(Uri uri) {
    RouteCenter.instance.dispatchUri(uri);
  }
}
