import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:mwf_app/service/pref.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/service/notification_count.dart';

class NotificationFirebase {
  final FirebaseMessaging firebaseMessaging;
  final BuildContext context;

  NotificationFirebase({
    @required this.context,
    @required this.firebaseMessaging,
  });

    NotificationFirebase initFirebaseMessaging() {
    // 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.."));
    firebaseMessaging.configure(
      onBackgroundMessage: backgrounfHandler,
      onMessage: (Map<String, dynamic> message) async {
        if (message.isNotEmpty) {
          
            print("::  " + message.toString());
            if(message.containsKey("data") && message['data'].containsKey("customerId")){
              print(AppUrl.CustomerID);
              print(message['data']['customerId']);
              AppUrl.CustomerID = message['data']['customerId'];
            }

            handleCountChat(message);
            NotificationCount.handleCountChatNotify(message);
            ManageNotify.showNotify(message);
          
        } else {
          message.clear();
        }
      },
      onLaunch: (Map<String, dynamic> message) async {
        
      },
      onResume: (Map<String, dynamic> message) async {
        if(message.containsKey("data")){
          print("onResume");
          String msg = message['data']['noti_type'].toString().toLowerCase();
          handleCountChat(message);
          if(msg == "chat"){
            NotificationCount.handleCountChatNotify(message);
          }else{
            NotificationCount.setCount(msg);
          }
          await NotificationCount.getCount();            
          FirebaseNotificationModel datas = FirebaseNotificationModel.fromJson(message['data']);
          var da = await ManageNotify.getDataNoti(jsonDecode(datas.toString()));
          print(da);
          // FirebaseNotificationModel data = FirebaseNotificationModel.fromJson(jsonDecode(da));
          // print("Name : " + data.chatFullname);
          // ManageNotify.selectNotifyOnResume(data);
          print("onResume2: $message");
          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");
    });
    
  }

  handleCountChat(message) async{
    print("Handle chat");
    int count = 0;
    if(message.isNotEmpty){
      if(message.containsKey("data") && message.containsKey("notification")){
        String type = message['data']['noti_type'].toString().toLowerCase();
        if(type == "chat") {
          count +=1;
          String chatMaster = message['data']['chatMasterId'];
          var data = await getPref("int" , chatMaster);
          if(data != null){
            setPref("int", chatMaster, data+count);
          }else if(data == null){
            setPref("int", chatMaster, count);
          }
          count = 0;
          print("Chat master ID :: " + chatMaster);
        }
      }
    }
  }
} // End off NotificationFirebase class

class FirebaseNotificationModel {
  String ca;
  String body;
  String time;
  String type;
  String title;
  String fileurl;
  String notiType;
  String typeChat;
  String accountId;
  String mwfNotiTypeId;
  String clickAction;
  String chatFullname;
  String chatMasterId;
  bool isGroupChat;
  bool isNewMessageChat;

  String customerId;
  String customerName;
  String roomType;
  String branchId;
  String saleInfoId;

  FirebaseNotificationModel({
    this.chatFullname,
    this.isNewMessageChat,
    this.mwfNotiTypeId,
    this.fileurl,
    this.typeChat,
    this.isGroupChat,
    this.ca,
    this.body,
    this.time,
    this.type,
    this.title,
    this.clickAction,
    this.accountId,
    this.chatMasterId,
    this.notiType,
    this.customerId,
    this.customerName,
    this.roomType,
    this.branchId,
    this.saleInfoId,
  });
 
  factory FirebaseNotificationModel.fromJson(Map<dynamic, dynamic> json) => FirebaseNotificationModel(
    ca: json["CA"] == null ? null : json["CA"],
    body: json["body"] == null ? null : json["body"],
    time: json["time"] == null ? null : json["time"],
    type: json["type"] == null ? null : json["type"],
    title: json["title"] == null ? null : json["title"],
    fileurl: json["fileurl"] == null ? null : json["fileurl"],
    typeChat: json["typeChat"] == null ? null : json["typeChat"],
    branchId: json["branchId"] == null ? null : json["branchId"],
    notiType: json["noti_type"] == null ? null : json["noti_type"],
    accountId: json["accountId"] == null ? null : json["accountId"],
    saleInfoId: json["saleInfoId"] == null ? null : json["saleInfoId"],
    mwfNotiTypeId: json["mwf_noti_type_id"] == null ? null : json["mwf_noti_type_id"],
    clickAction: json["click_action"] == null ? null : json["click_action"],
    chatMasterId: json["chatMasterId"] == null ? null : json["chatMasterId"],
    chatFullname: json["chatFullname"] == null ? null : json["chatFullname"],
    isGroupChat: json["isGroupChat"].toString() == "true" ? true : false,
    isNewMessageChat: json["isNewMessageChat"].toString() == "true" ? true : false,

    customerId: json["customerId"] == null ? null : json["customerId"],
    customerName: json["customerName"] == null ? null : json["customerName"],
    roomType: json["roomType"] == null ? null : json["roomType"],
  );

  Map<String, dynamic> toJson() => {
    "chatFullname": chatFullname == null ? null : chatFullname,
    "isNewMessageChat": isNewMessageChat == null ? null : isNewMessageChat,
    "mwf_noti_type_id": mwfNotiTypeId == null ? null : mwfNotiTypeId,
    "fileurl": fileurl == null ? null : fileurl,
    "typeChat": typeChat == null ? null : typeChat,
    "isGroupChat": isGroupChat == null ? null : isGroupChat,
    "CA": ca == null ? null : ca,
    "body": body == null ? null : body,
    "time": time == null ? null : time,
    "type": type == null ? null : type,
    "title": title == null ? null : title,
    "click_action": clickAction == null ? null : clickAction,
    "AccountId": accountId == null ? null : accountId,
    "chatMasterId": chatMasterId == null ? null : chatMasterId,
    "noti_type": notiType == null ? null : notiType,
    "customerId" : customerId,
    "customerName" : customerName,
    "roomType" : roomType,
    "branchId": branchId,
    "saleInfoId": saleInfoId,
  };
}
