import 'dart:async';

import 'package:app_links/app_links.dart';
import 'package:window_manager/window_manager.dart';

import '../../../shared/utils/app_logger.dart';
import '../trakt_api/trakt_credentials.dart';


class DeepLinkService {
  DeepLinkService._();

  static final DeepLinkService instance = DeepLinkService._();

  static const _tag = 'DeepLink';

  final AppLinks _appLinks = AppLinks();
  final StreamController<Uri> _controller = StreamController<Uri>.broadcast();
  bool _initialized = false;


  Stream<Uri> get uriStream => _controller.stream;

  Future<void> init() async {
    if (_initialized) return;
    _initialized = true;

    _appLinks.uriLinkStream.listen(
      _handle,
      onError: (Object e) => AppLogger.warn(_tag, 'uri stream error', e),
    );

    try {
      final initial = await _appLinks.getInitialLink();
      if (initial != null) _handle(initial);
    } catch (e) {
      AppLogger.warn(_tag, 'getInitialLink failed', e);
    }
  }

  void _handle(Uri uri) {
    if (uri.scheme != TraktCredentials.scheme ||
        uri.host != TraktCredentials.host) {
      return;
    }
    AppLogger.info(_tag, 'received ${uri.scheme}://${uri.host}');
    _bringToFront();
    _controller.add(uri);
  }

  Future<void> _bringToFront() async {
    try {
      await windowManager.show();
      await windowManager.focus();
    } catch (_) {}
  }
}
