import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:get/get.dart';
import '../commom/app_cache.dart';
import 'notification_service.dart';


class NotifyController extends GetxController {
  FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;

  @override
  void onInit() {
    configNotify();
    super.onInit();
  }

  configNotify() async {
    final token = await FirebaseMessaging.instance.getToken();
    print("FCM TOKEN: $token");
    AppCache().fcmToken = token;

    ///gives you the message on which user taps
    ///and it opened the app from terminated state
    FirebaseMessaging.instance.getInitialMessage().then((message) {
      if (message != null) {
        RemoteNotification? notification = message.notification;
        AndroidNotification? android = message.notification?.android;
        if (notification != null && android != null) {
          LocalNotificationService.display(message);
        }
      }
    });
    //backgroud work
    // FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

    ///forground work
    FirebaseMessaging.onMessage.listen((message) {
      if (message.notification != null) {
        LocalNotificationService.display(message);
      }
    });

    await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
      alert: true, // Required to display a heads up notification
      badge: true,
      sound: true,
    );


    ///When the app is in background but opened and user taps
    ///on the notification
    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      // AppUtils.shared.snackbarSuccess("Thông báo", "When the app is in background but opened and user taps");
    });
  }


  Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    LocalNotificationService.display(message);
  }
}
