/**
 * FCM nodejs module
 * @author Manish Yadav
 * @copyright Semusi Technologies PVT LTD
 */
'use strict'
const FCMAdmin = require('firebase-admin'),
    SemusiConfig = require('./../config'),
    Promise = require('bluebird');

/**
 * Send FCM message
 * @param registrationToken use for token to be need send fcm message
 *   [token1, token2]
 * @param data has custom data key value object like 
 *   :::: your_custom_data_key: 'your_custom_data_value'
 * @param notification has title and body in object format that will visiable to end user 
 * {
        title: 'Title of your push notification',
        body: 'Body of your push notification'
    }
 * Return array that haven't got FCM or error if occured  
 */
exports.initFCM = function(fcmCert, fcmDB){
    FCMAdmin.initializeApp({
        credential: FCMAdmin.credential.cert(require(fcmCert)),
        databaseURL: fcmDB
    });
}
exports.sendMessageWithPayload = function (registrationToken, data, fcmCert) {
    return new Promise((resolve, reject) => {
        try {
            sendMessage(registrationToken, data)
                .then((response) => {
                    let fcmNotSendIndexs = []; // store users list for that fcm not sent
                    if (response) {
                        response.results.forEach((result, index) => {
                            if (result.error) {
                                fcmNotSendIndexs.push(index);
                            }
                        });
                    }

                    return resolve(fcmNotSendIndexs)
                })
                .catch((error) => {
                    return reject(error)
                })
        }
        catch (error) {
            return reject(error);
        }
    });
}

// send FCM message and return reponse or error
let sendMessage = function (registrationToken, data) {
    return new Promise((resolve, reject) => {
        try {
            let payload = {
                data: data
            };

            let options = {
                priority: "high",
                timeToLive: 60 * 60 * 24
            }

            FCMAdmin.messaging().sendToDevice(registrationToken, payload, options)
                .then((response) => {
                    return resolve(response);
                })
                .catch((error) => {
                    return reject(error);
                })
        }
        catch (error) {
            return reject(error);
        }
    });
}

exports.sendMessage = sendMessage;

