let eventStringCommon = {},
    _ = require('underscore'),
    logger = require('../../logger'),
    moment = require('moment'),
    LRU = require("lru-cache"),
    options = {max:5000, length: function (n, key) { return n * 2 + key.length }},
    pgsql = require('./pgsql.utils'),
    eventstringCache = new LRU(options),
    sessionCache = new LRU(options),
    attributeValueCache = new LRU(options),
    Promise = require('bluebird');

(function (eventStringCommon) {

    Array.prototype.insert = function ( index, item ) {
        this.splice( index, 0, item );
    };

    //update existing attribute details
    let updateAttributeDetails = async function(UpdateAttributeDetailQuery) {
        let result = await pgsql.executeQuery(UpdateAttributeDetailQuery)
            .then((result) => { 
                return result;   
            })
            .catch((error)=>{
                logger.error(`error in fetching attribute detail => ${error}`);
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }

    //insert a row in attribute table
    let insertInAttributeTable = async function(insertAttributeQuery) {
        let result = await pgsql.executeQuery(insertAttributeQuery)
            .then((result) => {
                 
                return result;   
            })
            .catch((error)=>{
                logger.error(`error in inserting attribute => ${error}`);
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }



    //insert a batch in session table
    let insertInSessionTable = async function(finalString) {
        return new Promise((resolve, reject) => {
            pgsql.executeQuery(finalString)
            .then((result) => {
                 
                resolve(result);   
            })
            .catch((error)=>{
                logger.error(`error in inserting sessions => ${error}`);
                process.exit()
                let result = [];
                reject(result)
            })
        });    
    }
    //updating session length on the basis of event occurence
    let updateSessionLength = async function(finalString) {
        // let UpdateUserSessionLength = "Update "+ sessionTable + " set sessionlength = "+ eventtime +"-"+ startEventtime+" where id = "+ id +";"
        let result = await pgsql.executeQuery(finalString)
            .then((result) => {
                 
                return result;   
            })
            .catch((error)=>{
                logger.error(`error in updating session length => ${error}`);  
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }

     //update eventstring after inserting the events 
     let upsertAppUsersDataBatch = async function( UpdateString ) {
        let result = await pgsql.executeQuery(UpdateString)
            .then((result) => {
                 
                return result;   
            })
            .catch((error)=>{
                logger.error(`error in updating eventstring=> ${error}`);
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }

    //fetch app events data
    let insertAppEventsData = async function(appEventTable, event) {
        let currentDate = new Date();
        let currentTimestamp = currentDate.getTime()
        currentTimestamp = Math.round(currentTimestamp /1000);
        let AppEventsQuery = "insert into "+ appEventTable +" values(default,'"+ event +"', '{}', '[]', "+ currentTimestamp +" , "+ currentTimestamp +") returning id;";
        let result = await pgsql.executeQuery(AppEventsQuery)
            .then((result) => {
                    return result;   
            })
            .catch((error)=>{
                logger.error(`error in inserting in app events table => ${error}`);   
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }

    //match date regex
    let getMatchForDate = async function(eventString, dateregex){
        if(eventString==null){
            return false;
        }
        if(eventString.includes(dateregex)){
            return true;
        }
        else
            return false;
    }


    //prepare event string for the current sessions coming in the batch
    let prepareEventString = async function(iter, arraylength, user, appEventsData, appUsersTable, sessionTable, attributeTable, attributeValueTable, eventStringTable, eventStringColumn, eventStringCurrentColumn, appEventTable){
         
        //if iter is zero, meaning it is the starting of the batch, initialize all the strings used for batch processing
        if(iter == 0){
            finalUpdateString = ''  //string use to batch upsert eventstrings
            finalUpdateSessionLength = '';  //string used to batch update session length
            finalSessionString = '';    //String used to batch insert the sessions
        }

        let finaleventstring = ''//final string after all the events has occured
        if(eventstringCache.get(user[0].did)!=undefined){
            finaleventstring = eventstringCache.get(user[0].did) 
        }
        else{
            let ES = TotalCurrentDids.filter(function(v, j) {
                        return (v.did == user[0].did);
                     })

            if(ES!=undefined){
                if(ES.length==1){
                   finaleventstring = ES[0].eventstring 
                }
            }
            else{
                finaleventstring = '';
            }
        }  

        if(user.length>0){
            //compute date string as per required format
            let currentDate = new Date(user[0].dt);
            let day = currentDate.getDate();
            let month = currentDate.getMonth() + 1;
            let year = currentDate.getFullYear() % 100;
            let dateString = null
            if(day<10){
                dateString = "0" + day.toString()
            }
            else{
                dateString = day.toString()
            }
            if(month<10){
                dateString = dateString+"0"+month.toString()
            }
            else{
                dateString = dateString + month.toString()
            }
            dateString = dateString + year.toString()  
            
        } 
        let dateReg = 'D' + dateString
        let checkDate = await getMatchForDate(finaleventstring, dateReg);

        let pdid = 1; //initialize pdid with 1 for new session
        let starttime = 0; //for session length
        let endtime = 0;    //for session length
        let updateSession = 0;  //flag to check whether update session length is to be called or not
        let sessionArrayLength = 0; // store the index for details of current session to update session length
        if(user.length>0){
            //initialising session id as fetching from session table
            starttime = user[0].eventtime
            endtime = user[0].eventtime
            //filter all the sessions with this did and date and key
            let sessionArray = sessionCache.get(user[0].did+'_'+user[0].dt);
            let sessionid = []
            if(sessionArray == undefined){
                sessionArray = []
                sessionid= BatchSessionValues.filter(function(v, j) {
                            return (v.did == user[0].did && v.sid == user[0].sid);
                           })
                if(sessionid.length==0){
                    pdid = 1;
                }
                else{
                    pdid  = sessionid[0].pdid
                }
            }
            else{
                //update pdid, increment by 1 for current session
                pdid = sessionArray.length + 1
                //try to search if current session already exists
                sessionid = sessionArray.filter(function(v, j) {
                  return (v.sid == user[0].sid);
                })

            }
            

            //if current session do not exists
            if(!sessionid.length>0){
                //session id should not be null
                if(user[0].sid!=null&&user[0].sid!='null'){
                    //compute user array length
                    let userLen = user.length
                    //compute session length
                    let sessLength = user[userLen-1].eventtime - user[0].eventtime;
                    //make session object
                    let sessionObject = {
                        "did":user[0].did,
                        "sid":user[0].sid,
                        "eventtime": user[0].eventtime,
                        "key": "Session_Start",
                        "status":1,
                        "sessionlength": sessLength,
                        "dt":user[0].dt,
                        "platform": user[0].p,
                        "pdid":pdid
                    }
                    //replace double quotes from platform
                    let platform = sessionObject.platform.replace(/["]+/g, '')
                    //make the insert query
                    let insertSessionQuery = "insert into "+ sessionTable + " values (DEFAULT, '"+ sessionObject.did + "', '"+ sessionObject.sid +"'," + sessionObject.eventtime + ",'" + sessionObject.key + "', "+ sessionObject.status + ", "+ sessionObject.sessionlength + ", '" + sessionObject.dt + "', '" + platform + "', " + sessionObject.pdid + ") on conflict(did,sid,key) do nothing;"
                    //append this string for batch processing
                    finalSessionString = finalSessionString + insertSessionQuery
                    //push object to store in local cache
                    sessionArray.push(sessionObject)
                    sessionCache.set(user[0].did+'_'+user[0].dt,sessionArray);
                }
            }
            //if current session exists
            else{
                //mark this flag to 1 to update session length
                updateSession = 1;
                //set the pdid of existing sessions
                pdid = sessionid[0].pdid;
            }
        }

        //check if this date exists
        if(checkDate==false){
            finaleventstring = finaleventstring + 'D' + dateString;
        }

        let lastIndex = -1
        let eventStringlength = finaleventstring.length
        let startIndex = finaleventstring.indexOf('D'+dateString);
        if(finaleventstring.length>0){
            if(startIndex!=-1){
                for(let i = startIndex+1; i<eventStringlength; i++){
                    if(finaleventstring[i]=='D'){
                        break;
                    }
                    if(finaleventstring[i]=='E'&&finaleventstring[i+1]==pdid){
                        lastIndex = i;
                        break;
                    }
                }
            }
        }


        let currentSessionString = ''
       
        
        
        //for each event occuring in this batch, make an event string
        // const now5 = new Date()
        // let time5 = Math.round(now5.getTime())  
        for(let i = 0; i<user.length;i++){
            //getting event id for the current event
            let event = _.filter(appEventsData,{name:user[i].key})  
            if(!event.length>0){
                let eventid = await insertAppEventsData(appEventTable, user[i].key);
                if(eventid.length>0){
                   event = eventid[0]; 
                   appEventsData.push({name:user[i].key,id:event[0].id});
                }
            }
            //first check if session id is null, if yes ignore event
            if(user[i].sid!=null&&user[i].sid!='null'&&user[i].did!=null&&user[i].did!='null'&&user[i].did!=undefined&&user[i].did!='undefined'){
                //App_foreground and background are rejected and not to be stored in eventstring
                if(user[i].key!="App_Foreground"&&user[i].key!="App_Background"){                   

                    //if session id does not exists in the current eventstring
                    if(lastIndex==-1&&i==0){
                        currentSessionString = currentSessionString + "S" + pdid
                        currentSessionString = currentSessionString + "T" + user[i].eventtime   
                    }

                    //update end time for every event
                    endtime = user[i].eventtime; 
                                        //make session end object if key is Session End
                    if(user[i].key == "Session_End"){
                        let sessionObject = {
                            "did":user[i].did,
                            "sid":user[i].sid,
                            "eventtime": user[i].eventtime,
                            "key": "Session_End",
                            "status":0,
                            "sessionlength":0,
                            "dt":user[i].dt,
                            "platform": user[i].p,
                            "pdid":pdid
                        }

                        //replace double quotes from platform
                        let platform = sessionObject.platform.replace(/["]+/g, '')
                        //generate insert query
                        let insertSessionQuery = "insert into "+ sessionTable + " values (DEFAULT, '"+ sessionObject.did + "', '"+ sessionObject.sid +"'," + sessionObject.eventtime + ",'" + sessionObject.key + "', "+ sessionObject.status + ", "+ sessionObject.sessionlength + ", '" + sessionObject.dt + "', '" + platform + "', " + sessionObject.pdid + ") on conflict(did,sid,key) do nothing;"
                        //update string for batch insert
                        finalSessionString = finalSessionString + insertSessionQuery
                    }

                    //if current event is not session start, then insert that event as well
                    if(user[i].key!='Session_Start'&& user[i].key!='Session_End'){
                        // let breakingLength = finaleventstring.indexOf('E1');
                        // let stringLength = finaleventstring.length;
                        // let substr1 = finaleventstring.substring(0,breakingLength);
                        // let substr2 = finaleventstring.substring(breakingLength,stringLength);
                        // let substr3= 'B' + event[0].id + 'T' + user[i].eventtime
                        // finaleventstring = substr1 + substr3 + substr2;

                        currentSessionString = currentSessionString + 'B' + event[0].id + 'T' + user[i].eventtime

                        //adding logic for attribute here
                        if(user[i].segment!='{}'&&Object.keys(user[i].segment).length != 0 && user[i].segment.constructor === Object&&user[i].key!='_app_crash'&&user[i].key!='Inbox_Read'&&user[i].key!='Inbox_Viewed'&&user[i].key!='Inbox_Deleted'&&user[i].key!='Inbox_Unread'){
                            if(user[i].key=='Campaign_Viewed'|| user[i].key=='Campaign_Deleted'||user[i].key=='Campaign_Clicked'|| user[i].key=='Campaign_Received'){
                                validKeys = ['campid']
                                Object.keys(user[i].segment).forEach((key) => validKeys.includes(key) || delete user[i].segment[key]);
                            }
                            //loop over segment array
                            // const now1 = new Date()
                            // let time1 = Math.round(now1.getTime())
                            for(let key in user[i].segment){
                                if(user[i].segment[key]!=''&&user[i].segment[key]!=null){ 
                                    let valueDateTime = null //check for datatype date time
                                    let datatype = typeof(user[i].segment[key])
                                    //check if valus is int
                                    if(/^\d+$/.test(user[i].segment[key])){
                                        datatype = 'int'
                                    }
                                    //check if value is float
                                    else if(/^[0-9]+\.[0-9]+$/.test(user[i].segment[key])){
                                        datatype = 'float'
                                    }
                                    let datetime = null
                                    let datetimeValue = null
                                    //check if value can be converted to date time 
                                    if(datatype=='string'){
                                        valueDateTime =  Date.parse(user[i].segment[key])
                                        if((!isNaN(valueDateTime))&&valueDateTime>0){
                                            valueDateTime = valueDateTime/1000
                                            datetime = moment.unix(valueDateTime).format("DD-MM-YYYY");
                                            datetimeValue = datetime.replace(/-/g,'');
                                            datatype = "datetime" 
                                            
                                        }
                                    }
                                    //check for existing attribute
                                    let attributeKey = AttributeArray.filter(function(v, j) {
                                      return (v.key == user[i].key && v.name == key);
                                    })
                                    //if attribute does not exists
                                    if(!attributeKey.length>0){  
                                      break;
                                    }
                                    else{
                                        //define column name which is to be updated
                                        let column = ''
                                        if(datatype=='boolean'||datatype=='string'){
                                            //no change 
                                        } 
                                        //if datatype is datetime then first convert it into epoch and do the comparison and update the value in the table
                                        else if(datatype=='DateTime'){
                                            flag = 0;
                                            let num1 = attributeKey[0].datetimemin
                                            let num2 = attributeKey[0].datetimemax
                                            let str = num1.toString();
                                            let str2 = num2.toString();
                                            let str3 = str.substring(4, 8) +'-' + str.substring(2, 4) + '-' + str.substring(0, 2)
                                            let str4 = str2.substring(4, 8) +'-' + str2.substring(2, 4) + '-' + str2.substring(0, 2)
                                            let date1 = new Date(str3);
                                            let date2 = new Date(str4);
                                            let time1 = date1.getTime()/1000;
                                            let time2 = date2.getTime()/1000;

                                            if(valueDateTime>time1&&valueDateTime>time2){
                                                column = 'datetimemax'
                                                flag =1;
                                            }
                                            else if(valueDateTime<time1){
                                                column = 'datetimemin'
                                                flag=1;
                                            }
                                            //flag ==1 meaning, if value is to be update call the update attribute query
                                            if(flag==1){
                                                //make query
                                                let UpdateAttributeDetailQuery ="update " + attributeTable + " set " + column + " = '" + datetime + "' where id = " + attributeKey[0].id;
                                                let updateAttribute = await updateAttributeDetails(UpdateAttributeDetailQuery)   
                                            }

                                             
                                        }
                                        //if datatype is int, compare with min and max and update accordingly
                                        else if(datatype=='int'){
                                            flag = 0
                                            if(user[i].segment[key]>attributeKey[0].intmin&&user[i].segment[key]>attributeKey[0].intmax)
                                            {
                                                column = 'intmax'
                                                flag =1;
                                            }    
                                            else if(user[i].segment[key]<attributeKey[0].intmin)
                                            {
                                                column = 'intmin'
                                                flag =1;
                                            }
                                            if( user[i].segment[key] > 1000000000)
                                            {
                                                user[i].segment[key] = 1000000000 
                                            }
                                            //flag ==1 meaning, if value is to be update call the update attribute query
                                            if(flag==1&&user[i].segment[key] < 1000000000){
                                                //make query
                                                let UpdateAttributeDetailQuery ="update " + attributeTable + " set " + column + " = " + user[i].segment[key]  + " where id = " + attributeKey[0].id;
                                                let updateAttribute = await updateAttributeDetails(UpdateAttributeDetailQuery)   
                                            }
                                        } 
                                        //if datatype is float, compare with min and max and update accordingly
                                        else if(datatype=='float'){
                                            flag =0;
                                            if(user[i].segment[key]>attributeKey[0].floatmin&&user[i].segment[key]>attributeKey[0].floatmax)
                                            {
                                                column = 'floatmax'
                                                flag = 1;
                                            }    
                                            else if(user[i].segment[key]<attributeKey[0].floatmin)
                                            {
                                                column = 'floatmin'
                                                flag = 1;
                                            }
                                             if( user[i].segment[key] > 1000000000)
                                            {
                                                user[i].segment[key] = 1000000000
                                            }
                                            //flag ==1 meaning, if value is to be update call the update attribute query
                                            if(flag==1&&user[i].segment[key] < 1000000000){
                                                //make query
                                                let UpdateAttributeDetailQuery ="update " + attributeTable + " set " + column + " = " + user[i].segment[key] + " where id = " + attributeKey[0].id;
                                                let updateAttribute = await updateAttributeDetails(UpdateAttributeDetailQuery)   
                                            }
                                             
                                        }
                                        // breakingLength = finaleventstring.indexOf('E1');
                                        // stringLength = finaleventstring.length;
                                        // substr1 = finaleventstring.substring(0,breakingLength);
                                        // substr2 = finaleventstring.substring(breakingLength,stringLength);
                                        // substr3=  "A"+ attributeKey[0].id
                                        // finaleventstring = substr1 + substr3 + substr2;

                                        currentSessionString = currentSessionString + "A"+ attributeKey[0].id

                                    }
                                    //value cannot be empty or null
                                    if(user[i].segment[key]!=''&&user[i].segment[key]!=null){    
                                        
                                        //if datatype is string, insert value in attribute value table, else append as it is
                                        if(datatype == 'string'||datatype == 'boolean'){ 
                                            //check if value already exists

                                            let attributeValue = AttributeValueArray.filter(function(v, j) {
                                                                    return (v.attributeid == attributeKey[0].id && v.value == user[i].segment[key]);
                                                                 })
                                            if(attributeValue!=undefined){
                                                if(attributeValue.length>0){
                                                    if(attributeValue[0].id != null&&attributeValue[0].id!='null'){ 
                                                        // breakingLength = finaleventstring.indexOf('E1');
                                                        // stringLength = finaleventstring.length;
                                                        // substr1 = finaleventstring.substring(0,breakingLength);
                                                        // substr2 = finaleventstring.substring(breakingLength,stringLength);
                                                        // substr3=  "V"+ attributeValue[0].id
                                                        // finaleventstring = substr1 + substr3 + substr2;
                                                        currentSessionString  = currentSessionString + "V"+ attributeValue[0].id
                                                       
                                                    }  
                                                }  
                                            }
                                            else{
                                                break;
                                            }
                                            
                                        }
                                        //if datatype is int or float, add as it is to eventstring
                                        else if(datatype=='number'||datatype=='int'||datatype=='float'){
                                            if(user[i].segment[key]!=null&&user[i].segment[key]!='null'){
                                                if(datatype=='float'){
                                                    if(parseFloat(user[i].segment[key])){
                                                        let temp = parseFloat(user[i].segment[key]).toString();
                                                        // breakingLength = finaleventstring.indexOf('E1');
                                                        // stringLength = finaleventstring.length;
                                                        // substr1 = finaleventstring.substring(0,breakingLength);
                                                        // substr2 = finaleventstring.substring(breakingLength,stringLength);
                                                        // substr3=  "V" + temp
                                                        // finaleventstring = substr1 + substr3 + substr2;
                                                        currentSessionString  = currentSessionString + "V"+ temp
                                                           
                                                    }                                                    
                                                }
                                                else{
                                                    // breakingLength = finaleventstring.indexOf('E1');
                                                    // stringLength = finaleventstring.length;
                                                    // substr1 = finaleventstring.substring(0,breakingLength);
                                                    // substr2 = finaleventstring.substring(breakingLength,stringLength);
                                                    // substr3=  "V"+ user[i].segment[key]
                                                    // finaleventstring = substr1 + substr3 + substr2;
                                                    currentSessionString  = currentSessionString + "V"+ user[i].segment[key]
                                                    
                                                }
                                            }
                                        }
                                        //if datatype is datetime, add that to eventstring
                                        else if(!isNaN(valueDateTime)){
                                            if(datetime!=null&&datetime!='null'){   
                                                // breakingLength = finaleventstring.indexOf('E1');
                                                // stringLength = finaleventstring.length;
                                                // substr1 = finaleventstring.substring(0,breakingLength);
                                                // substr2 = finaleventstring.substring(breakingLength,stringLength);
                                                // substr3=  "V"+ datetimeValue
                                                // finaleventstring = substr1 + substr3 + substr2; 
                                                currentSessionString  = currentSessionString + "V"+ datetimeValue
                                            }
                                        }
                                    }
                                }   
                            }
                        }
                    }

                    if(i==user.length-1&&lastIndex==-1){
                        currentSessionString = currentSessionString + "E" + pdid
                        currentSessionString = currentSessionString + "T" + user[i].eventtime
                    }

                }
            }
        }

        // //if session already existed, then session length is to be updated
        // if(updateSession == 1&&sessionid!=undefined){
        //     if(endtime!=undefined&&starttime!=undefined&&sessionid[0].did!=undefined&&sessionid[0].sid!=undefined){
        //         let UpdateUserSessionLength = "Update "+ sessionTable + " set sessionlength = "+ endtime +"-"+ starttime+" where did = '"+ sessionid[0].did +"' and sid = '"+ sessionid[0].sid +"';"
        //         UpdateUserSessionLength = UpdateUserSessionLength.replace(/\\/g, '');    
        //         //update the string for batch update
        //         finalUpdateSessionLength = finalUpdateSessionLength +UpdateUserSessionLength;
        //     }
               
        // }        

        //if eventstring Array is not null
        if(currentSessionString.length>0){
             
            if(lastIndex !=-1){
                let substr1 = finaleventstring.substring(0,lastIndex)
                let substr2 = finaleventstring.substring(lastIndex,eventStringlength)
                finaleventstring = substr1 + currentSessionString + substr2;
            }
            else {
                let finalIndex = -1;
                for(let j = startIndex + 1; j<eventStringlength; j++){
                    if(finaleventstring[j]=='D'){
                        finalIndex = j;
                        break;
                    }
                }
                 
                if(finalIndex==-1){
                    finaleventstring = finaleventstring + currentSessionString;
                }
                else{
                   let substr1 = finaleventstring.substring(0,finalIndex)
                    let substr2 = finaleventstring.substring(finalIndex,eventStringlength)
                    finaleventstring = substr1 + currentSessionString + substr2; 
                }
            }

             

            finaleventstring = finaleventstring.replace(/null/, "");
            eventstringCache.set(user[0].did, finaleventstring);
            //update call for updating event string
            if(user.length>0&&user[0].did!=undefined&&user[0].did!='undefined'){
                //make upsert query for eventstring
                let UpsertUserDetailQuery = "update "+ appUsersTable + " set eventstring = '" + finaleventstring + "' where did= '" + user[0].did + "';"
                UpsertUserDetailQuery = UpsertUserDetailQuery.replace(/\\/g, '');
                finalUpdateString = finalUpdateString + UpsertUserDetailQuery;                        
            }
        }
        // if batch is completed and last user's eventstring is computed, then do batch processing
        if(iter == arraylength - 1){
            await insertInSessionTable(finalSessionString);
            // if(finalUpdateSessionLength!=''){
            //     updateSessionLength(finalUpdateSessionLength);
            // }
             
            await upsertAppUsersDataBatch(finalUpdateString); 
        }

        return iter;
    }


    //procces the cron 
    eventStringCommon.processEventStringCron = async function(events, uniqueUser, appEventsData, appUsersTable, sessionTable, attributeTable, attributeValueTable, eventStringTable, eventStringColumn, eventStringCurrentColumn, appEventTable){
        let uniqueUserArray = Array.from(uniqueUser[0]);
        logger.info(`unique User ARray Length ==>> ${uniqueUserArray.length}`)
        logger.info(`events Length ==>>  ${events.length}`)
        let arrayLength = uniqueUserArray.length 

        for(let i =0;i < uniqueUserArray.length; i++){
            let usersEvents = _.filter(events,{did_sid:uniqueUserArray[i]})
            //sort them on the basis of event time
            usersEvents.sort(function(a, b){return a.eventtime - b.eventtime});  


            //prepare the string once we have the events sorted accordingly
            let result = await prepareEventString(i, arrayLength, usersEvents, appEventsData, appUsersTable, sessionTable, attributeTable, attributeValueTable, eventStringTable, eventStringColumn, eventStringCurrentColumn, appEventTable);
            if(result==uniqueUserArray.length-1){
                logger.info("One Batch Completes here")
                return "success";
            }
        }


    }

    //fetch existing attribute details
    eventStringCommon.fetchAttributeValueDetails = async function(attributeValueTable) {
        let FetchAttributeValueDetailQuery = "select * from "+ attributeValueTable ;        
        let result = await pgsql.executeQuery(FetchAttributeValueDetailQuery)
            .then((result) => {
                 
                return result;   
            })
            .catch((error)=>{
                logger.error(`error in fetching attribute detail=> ${error}`);
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }

    //fetch existing attribute value details
    eventStringCommon.fetchAttributeValueDetailsWithValue = async function(attributeValueTable, attributeid, value) {
      let FetchAttributeValueDetailQuery = "select id from "+ attributeValueTable + " where value = '"+ value +"' and attributeid = "+ attributeid;
      let result = await pgsql.executeQuery(FetchAttributeValueDetailQuery)
      .then((result) => {
        logger.info(`fetching attribute value detail success ${result}`);
        return result;   
      })
      .catch((error)=>{
         logger.error(`error in fetching attribute value detail=> ${error}`);
        result = [];
      })
      return result;    
    }

    //fetch existing attribute details
    eventStringCommon.fetchAttributeDetails = async function(attributeTable) {
        let FetchAttributeDetailQuery = "select * from "+ attributeTable;
        let result = await pgsql.executeQuery(FetchAttributeDetailQuery)
            .then((result) => {
                 logger.info(`fetching attribute detail success`)
                return result;   
            })
            .catch((error)=>{
                logger.error(`error in fetching attribute detail=> ${error}`); 
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }


     //fetch existing attribute details
    eventStringCommon.fetchAttributeDetailsWithKey = async function(attributeTable, key, name) {
      let FetchAttributeDetailQuery = "select id, datatype from "+ attributeTable + " where name = '"+ name +"' and key = '"+ key +"'";
      let result = await pgsql.executeQuery(FetchAttributeDetailQuery)
      .then((result) => {
        logger.info(`fetching attribute detail success ${result}`);
        return result;   
      })
      .catch((error)=>{
        logger.error(`error in fetching attribute detail=> ${error}`);
        result = [];
      })
      return result;    
    }

    //fetch app events data
    eventStringCommon.fetchAppEventsData = async function(appEventTable) {
        let AppEventsQuery = "select DISTINCT name,id from "+ appEventTable ;
        let result = await pgsql.executeQuery(AppEventsQuery)
            .then((result) => {
                    return result;   
            })
            .catch((error)=>{
                logger.error(`error=> ${error}`); 
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }

     //fetch data from app Events table
    eventStringCommon.fetchAppEventsDataWithKey = async function(appEventTable, key) {
      let AppEventsQuery = "select DISTINCT id from "+ appEventTable + " where name = '"+ key +"'" ;
      //wait for response to get stored in result
      let result = await pgsql.executeQuery(AppEventsQuery)
      .then((result) => {
        return result;   
      })
      .catch((error)=>{
        logger.error(`error=> ${error}`);
        result = [];
      })
      return result;  
    }

    //fetch event count
    eventStringCommon.fetchEventCount = async function(countStatusTable,dt) {
        let AppEventsQuery = "select count from "+ countStatusTable + " where dt = '" + dt + "';" ;
        let result = await pgsql.executeQuery(AppEventsQuery)
            .then((result) => {
                    return result;   
            })
            .catch((error)=>{
                logger.error(`error=> ${error}`);
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }



    //fetch eventstrings for did 
    eventStringCommon.fetchEventStringFromDids = async function(finalQuery) {
        let result = await pgsql.executeQuery(finalQuery)
            .then((result) => {
                    return result;   
            })
            .catch((error)=>{
                logger.error(`error=> ${error}`);
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }

    //insert bulk attribute values
    eventStringCommon.insertBulkAttributeValues = async function(finalQuery) {
        let result = await pgsql.executeQuery(finalQuery)
            .then((result) => {
                    return result;   
            })
            .catch((error)=>{
                logger.error(`error=> ${error}`);
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }

    //select bulk attribute values
    eventStringCommon.selectBulkAttributeValues = async function(finalQuery) {
        let result = await pgsql.executeQuery(finalQuery)
            .then((result) => {
                    return result;   
            })
            .catch((error)=>{
                logger.error(`error=> ${error}`);
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }

    //select bulk session values
    eventStringCommon.selectBulkSessionValues = async function(finalQuery) {
        let result = await pgsql.executeQuery(finalQuery)
            .then((result) => {
                    return result;   
            })
            .catch((error)=>{
                logger.error(`error=> ${error}`);
                process.exit()
                let result = [];
                return result;
            })
        return result;    
    }


    eventStringCommon.helloworld = function (){
         
    }

}(eventStringCommon))     
module.exports = eventStringCommon;

