import 'dart:convert';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:mwf_app/home.dart';
import 'package:mwf_app/service/notification_firebase.dart';

import 'notification_count.dart';


class NotificationBackground {
  factory NotificationBackground.instance() => _instance;

  NotificationBackground._internal();

  static final _instance = NotificationBackground._internal();


  Future<void> startNotification() async {
    print("Handle firebase start...");
    await ManageNotify.initNotify();
    //HomePage();
    //await initFirebaseMessaging();
  }

  Future<void> initFirebaseMessaging() async {
    FirebaseMessaging firebaseMessaging = FirebaseMessaging();
    // firebaseMessaging.subscribeToTopic("pea_notification").whenComplete(()=> print("Everything is Okay.."));
    // firebaseMessaging.subscribeToTopic("fb0593bf-bee9-4350-845f-9aad236f7186").whenComplete(()=> print("Everything of group Okay.."));
    print("Handle firebase initFirebaseMessaging...");
    firebaseMessaging.configure(
      onBackgroundMessage: backgrounfHandler,
      onMessage: (Map<String, dynamic> message) async {
        if (message.isNotEmpty) {
          print("::  " + message.toString());
          
          
          if(message['data']['noti_type'].toString().toLowerCase() == "chat"){
            NotificationCount.handleCountChat(message);
            NotificationCount.handleCountChatNotify(message);
            ManageNotify.showNotify(message);
          }else{
            ManageNotify.showNotify(message);
          }
          
        } else {
          message.clear();
        }
      },
      onLaunch: (Map<String, dynamic> message) async {
        bool status = NotificationCount.getPrefBool("isLaunch") == null ? true : NotificationCount.getPrefBool("isLaunch");
        if(status == false){
          if(message.containsKey("data")){
            await ManageNotify.manageOnLaunch(message);
          }
        }
      },
      onResume: (Map<String, dynamic> message) async {
        if(message.containsKey("data")){
          print("onResume");
          // String msg = message['data']['noti_type'].toString().toLowerCase();
          // if(msg == "chat"){
          //   NotificationCount.handleCountChat(message);
          //   NotificationCount.handleCountChatNotify(message);
          // }else{
          //   NotificationCount.setCount(msg);
          // }
          await NotificationCount.getCount();            
          FirebaseNotificationModel datas = FirebaseNotificationModel.fromJson(message['data']);
          var da = await ManageNotify.getDataNoti(datas);
          FirebaseNotificationModel data = FirebaseNotificationModel.fromJson(jsonDecode(da));
          print("Name : " + data.chatFullname);
          ManageNotify.selectNotifyOnResume(data);
          message.clear();
        }
      },
    );
    firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, badge: true, alert: true));
    firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });

    firebaseMessaging.getToken().then((String token) {
      assert(token != null);
      print("Token : $token");
    });
  }
}