/**
Save App Inbox Data Into our Database Services using Common Connections
*/
var appInbox={},
    cacheApi = require('./semusi.cache.js'),
    logger = require('../../logger'),
    common = require('./common');
/**
 * App Inbox Data Used to Target for All Users which can not be Reachable to Push handlers
*/

(function (appInbox) {

    appInbox.saveAppInboxData=function(app_id,did, saveData){
        logger.info(`did Based Appinbox storing now`)
        //Save Data into Mongo Collection
        common.db.collection('app_inbox_'+ app_id).findOne({"did":did}, function(err, res) {
            if(res === null || res === undefined){
                // Inserted Object into Data 
                let insertedObject =  {"did":did,"updatedTime": new Date().getTime(),"data":[saveData]};
                //Inserted Object
                common.db.collection('app_inbox_'+ app_id).insertOne(insertedObject, function(err, res) {
                    if (res != null){
                        logger.info(`DID based Appinbox Stored`)
                        //Set first time data
                        cacheApi.setKey('app_inbox_'+ app_id + did, JSON.stringify(insertedObject));
                        let result = { "data":res, "msg":"1 document inserted"};
                        return result;
                    }else{
                        logger.info(`DID based Appinbox Failed`)
                        let result = { "data":res, "msg":"failed"};
                        return result;
                    }
                });
            }else{
                let updatedResponse = {"did":res.did};
                common.db.collection('app_inbox_'+ app_id).updateOne(updatedResponse, {$push:{"data":saveData}},{ $set:{updatedTime: new Date().getTime() } }, function(err, resultUpdatedData) {
                    if(err){
                        logger.error(`error while Updating data field in the AppInbox=> ${JSON.stringify(err)}`);  
                    }else{
                        common.db.collection('app_inbox_'+ app_id).findOne(updatedResponse, function(err, finalResponseData) {
                            // Error
                            if(err){
                                logger.error(`App Inbox Utility Error => ${JSON.stringify(err)}`);
                                // Final Response Data 
                            }else if(finalResponseData!= null){
                                common.db.collection('app_inbox_'+ app_id).updateOne(updatedResponse,{ $set:{"updatedTime": new Date().getTime() } }, function(err, resultUpdatedData) {
                                    if(err){
                                        logger.error(`Error while updating Appinbox=> ${err}`);
                                    }else{
                                        common.db.collection('app_inbox_'+ app_id).findOne(updatedResponse, function(err, finalResponseData) {
                                            if(err){  
                                                 // Failed Error   
                                                logger.error(`error While finding the Existing AppInbox => ${err}`);
                                            }else{
                                                logger.info(`Did based Appinbox Successfully `)
                                                cacheApi.setKey('app_inbox_'+ app_id + did, JSON.stringify(finalResponseData));
                                                return did;
                                            }
                                           
                                        });  
                                    }
                                });
                            }else{
                                let retVal=["result","failed"];
                                return retVal;
                            }
                        });
                    }
                });
            }
        });
    }
    
    appInbox.saveUserIDAppInboxdata=function(app_id,did,userID, saveData){
        logger.info(`UserId Based Appinbox storing now`)
        common.db.collection('app_inbox_'+ app_id).findOne({"userid":userID}, function(err, res) {  
            if(err){
                logger.error(`error While Finding the Exisitng AppInbox=> ${err}`);
            }else{
                
                if(res === null || res === undefined){
                    logger.info(`Data Not Found in Appinbox Redis  Null or undefined=== > ${res}`)
                    // Inserted Object into Data 
                    let insertedObject =  {"did":did,"userid":userID,"updatedTime": new Date().getTime(),"data":[saveData]};
                    //Inserted Object
                    common.db.collection('app_inbox_'+ app_id).insertOne(insertedObject, function(err, res) {
                        if (res != null){
                            //Set first time data
                            logger.info(`UserId based Appinbox Stored now inserting same in the redis ${insertedObject}`)
                            cacheApi.setKey('app_inbox_'+ app_id+userID, JSON.stringify(insertedObject));
                            let result = { "data":res, "msg":"1 document inserted"};
                            return result;
                        }else{
                            logger.info(`UserId based Appinbox Failed`)
                            let result = { "data":res, "msg":"failed"};
                            return result;
                        }
                    });
                }else{                 
                    logger.info(`Data Found in appinbox in db will update the data `)              
                    let updatedResponse = {"_id":res._id};
                    logger.info(`updated response :: ${JSON.stringify(updatedResponse)} && saveData => ${JSON.stringify(saveData)}`);
                    common.db.collection('app_inbox_'+ app_id).updateOne(updatedResponse, {$push:{"data":saveData}}, function(err, resultUpdatedData) {
                        if(err){
                            logger.error(`error while Pushing the data in UserID Appinbox=> ${JSON.stringify(err)}`);
                        }else{
                             logger.info(`Pushed the data into the db`)
                            common.db.collection('app_inbox_'+ app_id).updateOne(updatedResponse,{ $set:{"updatedTime": new Date().getTime() } }, function(err, resultUpdatedData) {
                                if(err){
                                    logger.error(`error While Updating the Appinbox => ${err}`);
                                }else{
                                    logger.info(`Now getting the data again from db and setting it in the redis`)
                                common.db.collection('app_inbox_'+ app_id).findOne(updatedResponse, function(err, finalResponseData) {
                                    if(err){
                                        logger.error(`App Inbox Utility Error =>=> ${err}`);
                                    }else if(finalResponseData!= null || finalResponseData == undefined){
                                        logger.info(`UserID based Appinbox Successfully `)
                                        logger.info(` UserID based Appinbox Setting as  finalResponseData:====>,${JSON.stringify(finalResponseData)}`)
                                        cacheApi.setKey('app_inbox_'+ app_id+userID, JSON.stringify(finalResponseData));
                                        return finalResponseData;
                                    }else{
                                        let retVal=["result","failed"];
                                        logger.error(`Error while setting Data in User id based appinbox as ${finalResponseData}`)
                                        return retVal;
                                    }
                                });
                                }
                            });
                        }
                    });
                }
            }
        });
    }

}(appInbox));

module.exports = appInbox;
