const { JWT } = require('google-auth-library');
const fetch = require('node-fetch');
const db = require("./dbService.js");

const sendFcmNotification = async (fcmToken,deviceType,title,message,type,id) => {
        const serviceAccount = require('../../../storage/app/fcm/valo-app-firebase.json');
        const target = fcmToken;
        // const payload = {
        //     message: {
        //         token: target,
        //         data: {
        //             title: title,
        //             body: message,
        //             type: String(type),
        //             id: String(id)
        //         },
        //         notification: {
        //             title: title,
        //             body: message,
        //         },
        //     }
        // };
         if(deviceType == 'android')
            {
                var payload = {
                    message: {
                        token: target,
                        data: {
                            title: title,
                            body: message,  
                            type: String(type),
                        }
                    }
                };
            }
            else
            {
                var payload = {
                    message: {
                        token: target,
                        data: {
                            title: title,
                            body: message,
                            type: String(type),
                        },
                        // notification: {
                        //     title: title,
                        //     body: message,
                        // },
                    }
                };
            }
        console.log(payload,"payload");
        // const url = 'https://fcm.googleapis.com/v1/projects/valo-app-355d0/messages:send';
        const url = 'https://fcm.googleapis.com/v1/projects/valo-4dcf7/messages:send';
        const client = new JWT({
            email: serviceAccount.client_email,
            key: serviceAccount.private_key,
            scopes: ['https://www.googleapis.com/auth/firebase.messaging'],
        });
        const accessToken = await client.authorize().then(response => response.access_token);
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${accessToken}`,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });
        const result = await response.json();
        console.log(result, "result");
        return result;
}
 
// const messageOfNotification = async(notifyType, username, name) => {
//     const types = await notificationsTypes();

//     let data;

//     switch (notifyType) {
//         case "raiseHandeRequest":
//             data = {
//                 type: types['raiseHandeRequest'],
//                 title: 'Raise Hand Request',
//                 message: `${username} has sent raise hand request to  you.`
//             };
//             break;
//         case "sendMessage":
//             data = {
//                 type: types['sendMessage'],
//                 title: 'Send Message',
//                 message: `${username} has sent message to  you.`
//             };
//             break;
//         case "acceptRaiseHandRequest":
//             data = {
//                 type: types['acceptRaiseHandRequest'],
//                 title: 'Accept Hand Raise Request',
//                 message: `${username} has accepted your hand raise request.`
//             };
//             break;
//         case "sendReplyMessage":
//             data = {
//                 type: types['sendReplyMessage'],
//                 title: `${username} mentioned you `,
//                 message: `${username} mentioned you in the ${name} crib chat.`
//             };
//             break;
//         case "follow":
//             data = {
//                 type: types['follow'],
//                 title: 'Someone follow',
//                 message: `${username} is following you.`
//             };
//             break;    
//         default:
//             data = {
//                 type: '',
//                 title: '',
//                 message: ''
//             };
//     }

//     return data;
// }

// const notificationsTypes = async () => {
//     return {
//         raiseHandeRequest: 'raiseHandeRequest',
//         sendMessage: 'sendMessage',
//         acceptRaiseHandRequest: 'acceptRaiseHandRequest',
//         sendReplyMessage: 'sendReplyMessage',
//         follow: 'follow'
//     };
// }

// const addNotficationFun = async (senderID,receiverID,notifyType,username,name,isMutiple,type,fieldName,fieldValued) => 
// {
//     console.log(senderID,"senderID",receiverID,"receiverID" )
//     const datetime = new Date().toISOString().slice(0, 19).replace('T', ' ');
//     const messageData = await messageOfNotification(notifyType,username,name);
//     if(isMutiple == 1)
//     {
//         const receiverDetail = "SELECT * FROM tbl_users WHERE id = " + receiverID + " AND isNotification = 1";
//         const isUserExist = await new Promise((resolve, reject) => {
//             db.query(receiverDetail, function (err, result) {
//                 if (err) return reject(err);
//                 resolve(result);
//             });
//         });
//         if(isUserExist.length === 1){ 
//             sqlQuery = "INSERT INTO tbl_notifications (senderID,receiverID,notifyType,type,title,message,status,created_at,"+ fieldName +") VALUES (?, ?, ?, ?, ?,?,?,?,?)";
//             await new Promise((resolve, reject) => {
//                 db.query(sqlQuery,[senderID,receiverID,messageData.type,type, messageData.title, messageData.message, 1, datetime,fieldValued], function (err, result) {
//                     if (err) return reject(err);
//                     resolve(result);
//                 });
//             });
//             console.log(sqlQuery, "sqlQuery");
//             row = JSON.parse(JSON.stringify(isUserExist[0]))
//             console.log(row,row.deviceToken, "adasd");
//             await sendFcmNotification(row.deviceToken,messageData.title,messageData.message,messageData.type,fieldValued)
//         }
//     }
//     else
//     {
//         let payload = [];
//         let deviceTokens = [];
    
//         for (let values of receiverID) {
//             const receiverDetail = "SELECT * FROM tbl_users WHERE id = " + values.peopleID + " AND isNotification = 1 AND status = 1";
//             console.log(receiverDetail);
//             const isUserExist = await new Promise((resolve, reject) => {
//                 db.query(receiverDetail, function (err, result) {
//                     if (err) return reject(err);
//                     resolve(result);
//                 });
//             });
//             if(isUserExist.length === 1)
//             { 
//                 user = JSON.parse(JSON.stringify(isUserExist[0]))
//                 //const user = await getUserByID(values.peopleID);
//                 if (user) 
//                 {
//                   /*  payload.push({
//                         senderID: senderID,
//                         receiverID: user.id,
//                         notifyType: messageData.type,
//                         type: messageData.type,
//                         fieldName: fieldValued,
//                         title: messageData.title,
//                         message: messageData.message,
//                         status: 1,
//                         created_at: new Date().toISOString().slice(0, 19).replace('T', ' ')
//                     });*/
//                     sqlQuery = "INSERT INTO tbl_notifications (senderID,receiverID,notifyType,type,title,message,status,created_at,"+ fieldName +") VALUES (?, ?, ?, ?, ?,?,?,?,?)";
//                     await new Promise((resolve, reject) => {
//                         db.query(sqlQuery,[senderID,user.id,messageData.type,type, messageData.title, messageData.message, 1, datetime,fieldValued], function (err, result) {
//                             if (err) return reject(err);
//                             resolve(result);
//                         });
//                     });    
//                     //deviceTokens.push(user.deviceToken);
//                     await sendFcmNotification(user.deviceToken,messageData.title,messageData.message,messageData.type,fieldValued)
//                     // Assuming notificationData is a function that sends notifications to devices
//                 }
//             }
//         }
//         return true; 
//     }
// }
 
// const directNotification = async (senderID,receiverID,notifyType,message,username,fieldValued) => 
// {
//     console.log(receiverID,"RECEIVER ID");
//     const messageData = await messageOfNotification(notifyType,username,'');
//     const receiverDetail = "SELECT * FROM tbl_users WHERE id = " + receiverID + " AND isNotification = 1";
//     const isUserExist = await new Promise((resolve, reject) => {
//         db.query(receiverDetail, function (err, result) {
//             if (err) return reject(err);
//             resolve(result);
//         });
//     });
//     if(isUserExist.length === 1){ 
//         row = JSON.parse(JSON.stringify(isUserExist[0]))
//         await sendFcmNotification(row.deviceToken,username,message,messageData.type,fieldValued)
//     }
// }
    
module.exports = {
    sendFcmNotification
}        