import 'dart:io';

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

final msgLog = Logger('backgroundMessageHandler');

Future<dynamic> backgroundMessageHandler(Map<String, dynamic> message) async {
  if (message.containsKey('data')) {
    // Handle data message
    final dynamic data = message['data'];
    msgLog.info("background onMessage: $message");
  }

  if (message.containsKey('notification')) {
    // Handle notification message
    final dynamic notification = message['notification'];
  }
}

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

  FirebaseMessaging _firebaseMessaging;

  MessagingFCM(OnNotify onMessage,
      {OnNotify onLaunch, OnNotify onResume, OnSetupComplete onSetupComplete}) {
    _firebaseMessaging = FirebaseMessaging();
    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        log.info("onMessage: $message");
        if (onMessage != null) _onNotify(message, onMessage);
      },
      onBackgroundMessage: Platform.isIOS ? null : backgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        log.info("onLaunch: $message");
        if (onLaunch != null) _onNotify(message, onLaunch);
      },
      onResume: (Map<String, dynamic> message) async {
        log.info("onResume: $message");
        if (onResume != null) _onNotify(message, onResume);
      },
    );
    _firebaseMessaging
        .requestNotificationPermissions(const IosNotificationSettings());
    _firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      log.info("Settings registered: $settings");
    });
    _firebaseMessaging.getToken().then((String token) {
      if (onSetupComplete != null) onSetupComplete(token);
      log.info("Messaging Token:$token");
    });
  }

  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);
  }
}
