/* Update Data to IOS Users*/
'use strict';
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://10.0.0.5:27017/";
var pgsqlUtils = require('./../../utils/pgsql.utils');
//Get Data from Mongo
MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("aiproddb");
         let skip = parseInt(process.argv[2]);
         let query = {did:'a573704d-7ffd-4a81-8b2f-454f0a50e79d'};
          
         dbo.collection("app_users5fa41afe6fc1e678a8344311").find().skip(skip).limit(1000).toArray(function(err, result) {
             if (err) throw err;
             result.forEach(element => {
                if(element.did){
                    let queryCitus = "select count(*) from  app_users_5fa41afe6fc1e678a8344311 where did = '" + element.did + "'";
                    // Citus Query
                    pgsqlUtils.executeQuery(queryCitus)
                        .then(res =>{
                            let countData = JSON.parse(JSON.stringify(res));  
                            let dataSet= countData[0][0].count;
                            var ci; 
                            if(isJson(element._custom)) {
                                element._custom = JSON.parse(element._custom);
                            }  
                            if(Object.keys(element._custom).length > 0){
                                let data =  Object.values(element._custom);
                                if(isJson(data[0])) {
                                    data = JSON.parse(data[0]);
                                }
                                if(data.length) {   
                                    ci = data.join("\r,\n");
                                }else{
                                    ci= '';
                                }
                            }else{
                                ci = '';
                            }

                            //if(dataSet == 0){
                                
                                let queryCitus = "update app_users_5fa41afe6fc1e678a8344311 SET _custom_userid = '" + ci + "' where did = '" + element.did + "'";
                                    // Citus Query
                                pgsqlUtils.executeQuery(queryCitus)
                                    .then(res =>{
                                       
                                    })
                                    .catch(error =>{
                                         
                                    });
                                                
                           // }
                    })
                }
             });
         });
});

 function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
          return false;
    }
      return true;
  } 
