import 'package:fcs/data/services/messaging_service.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:logging/logging.dart';

final msgLog = Logger('backgroundMessageHandler');

Future<void> backgroundMessageHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  msgLog.info("background onMessage: $message");
}

class MessagingFCM {
  final log = Logger('MessagingFCM');

  late FirebaseMessaging _firebaseMessaging;

  MessagingFCM(OnNotify onMessage,
      {OnNotify? onLaunch,
      OnNotify? onResume,
      OnSetupComplete? onSetupComplete}) {
    _firebaseMessaging = FirebaseMessaging.instance;
    init(onMessage: onMessage, onSetupComplete: onSetupComplete);
  }

  init({OnNotify? onMessage, OnSetupComplete? onSetupComplete}) async {
    NotificationSettings settings = await _firebaseMessaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );

    print('User granted permission: ${settings.authorizationStatus}');

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      log.info("onMessage: $message");
      if (onMessage != null) _onNotify(message.data, onMessage);

      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
      }
    });

    try {
      String? token = await _firebaseMessaging.getToken();
      if (onSetupComplete != null && token != null) onSetupComplete(token);
      log.info("Messaging Token:$token");
    } on Exception catch (e) {
      log.shout("Unable to get messing token:$e");
    }
  }

  Future<void> subscribeToTopic(String topic) {
    return _firebaseMessaging.subscribeToTopic(topic);
  }

  _onNotify(Map<String, dynamic> message, OnNotify onNotify) {
    var data = message['data'] ?? message;
    onNotify(Map<String, dynamic>.from(message));
  }

  Future<void> unsubscribeToTopic(String topic) {
    return _firebaseMessaging.unsubscribeFromTopic(topic);
  }
}
