/**
 * Web push nodejs module
 * @author Manish Yadav
 * @copyright Semusi Technologies PVT LTD
 */
'use strict'
const webPush = require('web-push'),
logger = require('../../logger'),
semusiConfig = require('../config'),
    Promise = require('bluebird');

/**
 * const payload = {
            title: req.body.title,
            message: req.body.message,
            url: req.body.url,
            ttl: req.body.ttl,
            icon: req.body.icon,
            image: req.body.image,
            badge: req.body.badge,
            tag: req.body.tag
        };

        const pushSubscription = {
            endpoint: subscription.endpoint,
            keys: {
                p256dh: subscription.keys.p256dh,
                auth: subscription.keys.auth
            }
        };

         vapidDetails: {
            subject: 'http://localhost:4000',
            privateKey: keys.privateKey,
            publicKey: keys.publicKey
        }

 * @param {*} pushSubscription // pushSubscription has user infomation 
 * @param {*} data // webpush payload
 * @param {*} config  // web push privatekey and public key inside obj
 */
exports.pushNotifications = function (user, data, config) {
    return new Promise((resolve, reject) => {
        const pushPayload = JSON.stringify(data);
        const pushOptions = {
            vapidDetails: config,
            TTL: (60*60)*24,
            headers: {}
        };
        // if proxy is present in .env then add in the option
        if(semusiConfig.proxyUrl){
            logger.info(`Proxy Enabled ! Now adding Proxy in Push Options`)
            pushOptions.proxy = semusiConfig.proxyUrl
        }
        logger.info(`web push pushOptions : ${pushOptions}`);
        logger.info(`web push user : ${user}`);
        logger.info(`web push pushPayload : ${pushPayload}`);
        webPush.sendNotification(
            user,
            pushPayload,
            pushOptions
        ).then((value) => {
            return resolve({
                status: true,
                endpoint: user.endpoint,
                data: value
            });
        }).catch((err) => {
            return reject({
                status: false,
                endpoint: user.endpoint,
                data: err
            });
        });
    });
}