import 'package:didvan/models/notification_data.dart';
import 'package:didvan/models/notification_message.dart';
import 'package:didvan/services/app_home_widget/home_widget_repository.dart';
import 'package:didvan/services/app_initalizer.dart';
import 'package:didvan/services/notification/notification_service.dart';
import 'package:didvan/services/storage/storage.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';

class FirebaseApi {
  final _firebaseMessaging = FirebaseMessaging.instance;
  static String? fcmToken;

  Future<void> initNotification() async {
    try {
      fcmToken = await _firebaseMessaging.getToken();
      if (kDebugMode) {
        print("fCMToken: $fcmToken");
      }
    } catch (e) {
      e.printError();
    }

    _firebaseMessaging.requestPermission(
      alert: true,
      announcement: true,
      badge: true,
      carPlay: false,
      criticalAlert: true,
      provisional: true,
      sound: true,
    );

    final initMsg = await FirebaseMessaging.instance.getInitialMessage();

    if (initMsg != null) {
      try {
        NotificationMessage data = NotificationMessage.fromJson(initMsg.data);
        HomeWidgetRepository.data = data;
        if (kDebugMode) {
          print("data: ${HomeWidgetRepository.data}");
        }
        await HomeWidgetRepository.decideWhereToGoNotif();
        await StorageService.delete(
            key: 'notification${AppInitializer.createNotificationId(data)}');
      } catch (e) {
        e.printError();
      }
    }

    FirebaseMessaging.onMessageOpenedApp.listen((initMsg) async {
      try {
        NotificationMessage data = NotificationMessage.fromJson(initMsg.data);
        HomeWidgetRepository.data = data;
        if (kDebugMode) {
          print("data: ${HomeWidgetRepository.data}");
        }
        await HomeWidgetRepository.decideWhereToGoNotif();
        await StorageService.delete(
            key: 'notification${AppInitializer.createNotificationId(data)}');
      } catch (e) {
        e.printError();
      }
    });

    FirebaseMessaging.onMessage.listen((event) => handleMessage(event));
  }

  void handleMessage(RemoteMessage? message) async {
    if (message == null) return;
    //do ever you want with message
    // if (kDebugMode) {
    if (kDebugMode) {
      print("forground: ${NotificationData.fromJson(message.data).toJson()}");
    }
    // }
    try {
      await NotificationService.showFirebaseNotification(message);
    } catch (e) {
      e.printError();
    }
  }
}
