const pgsql = require('../../utils/pgsql.utils')
const common = require('./../../utils/common.js')

const fetchData = async (appid, did) =>{
    try{
    return new Promise(async(resolve, reject) => {
        //check if appid and did provided
        if(appid == null){
            return reject('AppID not provided')
        }
        else if(did == null){
            return reject('DID not provided')
        }
        else {  

            let result = {}

            //all fields of app_users in pgsql
            let pgsqlFields = await pgsql.executeQuery("select * from app_users_"+appid+" where did = '"+did+"';")
            .then((result) => {
                return result;   
            })
            .catch((error)=>{
                reject("error", error)
            })
            if( pgsqlFields[0][0] != null || pgsqlFields[0][0] != undefined){
            result['pgsqlFields'] = pgsqlFields[0][0]
        }
            //last 50 events for the user
            let last50Events = await pgsql.executeQuery("select key, eventtime from events_"+appid+" where did = '"+did+"' order by eventtime DESC limit 50;")
            .then((result) => {
                return result;   
            })
            .catch((error)=>{
                reject("error", error)
            })
            result['last50Events'] = last50Events[0]

            //all fields of app_users mongodb
            let mongoFields = common.db.collection('app_users'+appid).find({ "did" : did }).toArray(function (err, res) {
                result['mongoFields'] = res[0]
                                                                                                                             
                //push token for device in mongodb
                let pushToken = common.db.collection('usertoken_'+appid).find({ "did" : did }).toArray(function (err, res) {
                    if(res.length == 0) result['pushToken'] = "";
                    else result['pushToken'] = res[0].pushtoken

                    //total count and json data of appinbox entry in mongodb
                    let appInbox = common.db.collection('app_inbox_'+appid).find({ "did" : did }).toArray(function (err, res) {
                        if(res.length == 0){
                            result['appInbox'] = {
                                count: res,
                                data: res
                            }
                        }
                        else{
                            result['appInbox'] = {
                                count: res[0].data.length,
                                data: res[0].data
                            }
                        }
                        
                        resolve(result)
                    });
                });
            });
        }
    })
}catch(err){
    throw err
}
}

module.exports = {
    fetchData: fetchData
}