const common = require("../../utils/common");
const FCM = require('fcm-node');
const path = require('path');

module.exports = {
    test: (req, res) => {
        const payload = req.body;
        const appid = payload.app_id ?? '';
        const did = payload.did ?? '';
        const data = payload.data ?? '';
        if (did != '' && appid != '') {
            //function call for get App Detsils
            getAppSettingDetails(appid).then((appDetails) => {
                //function call for get Users Detsils
                getUserDetails(appid, did).then((userData) => {
                    let app = appDetails[0];
                    if (userData[0].p == 'Android') {
                        let fcmKey = app.isappmodeproduction ? app.fcmKey_prod : app.fcmKey_dev;
                        let token = userData[0].fcmid ?? false;
                        if (token) {
                            //function call for send Android Push
                            sendAndroidPush(token, fcmKey, data).then((pushResult) => {
                                return res.status(200).json({
                                    status: true,
                                    result: {
                                        appDetails: appDetails,
                                        userData: userData,
                                        pushResult: pushResult
                                    },
                                });
                            })
                                .catch(error => {
                                    logger.error(`catch error ::>>>${error}`);
                                    return res.status(200).json({
                                        status: true,
                                        result: {
                                            errmsg: "push error",
                                            err: error
                                        },
                                    });
                                });

                        } else {
                            return res.status(200).json({
                                status: true,
                                result: {
                                    appDetails: appDetails,
                                    userData: userData,
                                    msg: "Token Not Found"
                                },
                            });
                        }
                    } else {
                        let cert3 = app.isappmodeproduction ? app.ios_cert3 : app.dev_ios_cert3;
                        let gcmid = userData[0].gcmid ?? false;
                        if (gcmid) {
                            //function call for iOS push setting 
                            common.checkAppleCertificate(appid, cert3, function (resCertificate) {
                                if (resCertificate) {
                                    //prepare iOS setting Object with mode
                                    let options = new Object();
                                    options.cert = path.join(__dirname, "../../../frontend/express/public/appcertificates/" + appid + "/" + cert3);
                                    options.production = app.isappmodeproduction;
                                    options.keyid = options.production ? app.ios_keyid : app.dev_ios_keyid;
                                    options.teamid = options.production ? app.ios_teamid : app.dev_ios_teamid;
                                    options.pkg = options.production ? app.ios_topic : app.dev_ios_topic;
                                    options.ios_auth_type = options.production ? app.ios_key_type : app.dev_ios_key_type;
                                    options.topic = options.production ? app.ios_topic : app.dev_ios_topic;
                                    //function call for send iOS Push
                                    sendiOSPush(gcmid, options, data).then((pushResult) => {
                                        return res.status(200).json({
                                            status: true,
                                            result: {
                                                iOSPushSetting: options,
                                                appDetails: appDetails,
                                                userData: userData,
                                                pushResult: pushResult
                                            },
                                        });
                                    })
                                        .catch(error => {
                                            logger.error(`catch error ::>>>${error}`);
                                            return res.status(200).json({
                                                status: true,
                                                result: {
                                                    errmsg: "push error",
                                                    err: error
                                                },
                                            });
                                        });
                                } else {
                                    return res.status(200).json({
                                        status: true,
                                        result: {
                                            appDetails: appDetails,
                                            userData: userData,
                                            msg: "P8 File does not exist on server"
                                        },
                                    });
                                }
                            });
                        } else {
                            return res.status(200).json({
                                status: true,
                                result: {
                                    appDetails: appDetails,
                                    userData: userData,
                                    msg: "GCM ID not exist"
                                },
                            });
                        }
                    }
                })
                    .catch(error => {
                        logger.error(`catch error ::>>>${error}`);
                        return res.status(200).json({
                            status: true,
                            result: {
                                msg: "user details error ::>>>",
                                err: error
                            },
                        });
                    });
            })
                .catch(error => {
                    logger.error(`catch error ::>>>${error}`);
                    return res.status(200).json({
                        status: true,
                        result: {
                            msg: "app setting error",
                            err: error
                        },
                    });
                });

        } else {
            return res.status(200).json({
                status: true,
                result: {
                    msg: "Please send appid and did ",
                    err: "Your not sendin mandatory fields"
                },
            });
        }
    }
}

// getUserDetails private function toget user data to send push 
getUserDetails = function (appid, did) {
    return new Promise((resolve, reject) => {
        common.db.collection('app_users' + appid).find({ 'did': did, }, { _id: -1, did: 1, history: 1, p: 1, fcmid: 1, gcmid: 1, d: 1, av: 1 }).toArray(function (err, users) {
            if (!err) {
                resolve(users);
            } else {
                reject(err);
            }
        });

    })
}

// getAppSettingDetails private function toget app data to send push 
getAppSettingDetails = function (appid) {
    return new Promise((resolve, reject) => {
        common.db.collection('apps').find({ '_id': common.db.ObjectID(appid), }, { _id: -1, name: 1, push_notification: 1, isappmodeproduction: 1, fcmKey_prod: 1, fcmKey_dev: 1, ios_cert3: 1, dev_ios_cert3: 1, ios_keyid: 1, dev_ios_keyid: 1, ios_teamid: 1, dev_ios_teamid: 1, ios_topic: 1, dev_ios_topic: 1, ios_key_type: 1, dev_ios_key_type: 1 }).toArray(function (err, apps) {
            if (!err) {
                resolve(apps);
            } else {
                reject(err);
            }
        });
    })
}

// getAppSettingDetails private function toget app data to send push 
sendAndroidPush = function (fcmid, fcmKey, data) {
    return new Promise((resolve, reject) => {
        let fcmNotification = new FCM(fcmKey);
        let message = {
            registration_ids: fcmid,
            priority: "high",
            content_available: true
        }
        if (data != '') {
            message.data = data
        } else {
            message.data = {
                title: "this is test title from appice",
                description: "this is test desc from appice",
            }
        }
        //push send with payload 
        fcmNotification.send(message, function (err, response) {
            if (err) {
                reject(err);
            } else {
                resolve(response);
            }
        });
    })
}


// getAppSettingDetails private function toget app data to send push 
sendiOSPush = function (gcmid, optionsData, data) {
    return new Promise((resolve, reject) => {
        let options = {
            token: {
                key: optionsData.cert,
                keyId: optionsData.keyid,
                teamId: optionsData.teamid
            },
            production: optionsData.production
        };
        //Create Connection
        let apnProvider = new apn.Provider(options);
        let note = new apn.Notification();
        note.expiry = Math.floor(Date.now() / 1000) + 3600;
        note.badge = 1;
        note.mutableContent = 1;
        note.contentAvailable = 1;
        if (data != '') {
            note.payload = data
        } else {
            note.payload = {
                title: "this is test title from appice",
                body: "this is test body from appice",
            }
        }
        note.topic = optionsData.topic;

        apnProvider.send(note, gcmid).then((result) => {
            if (Array.isArray(result.sent) && result.sent.length) {
                resolve(result);
            } else {
                reject(result);
            }
        });
    })
}