var backup = {},
    common = require('./../../utils/common.js'),
	logger = require('../../../logger'),
    moment = require('moment');

(function (backup) {

	backup.updateBackup = function(datajson,appid){
		var mobileid = datajson.mobileid;

		//Check if wifi data exists, then do bulk insert for wifi data.
		if(datajson.wifi){
		    bulkInsertWifiDataRoot(appid,mobileid,datajson.wifi,function(err,result){
	    		if(err){
					logger.error(`error is => ${err}`);
	    		}
	    	});		
	    }
	    //Check if internetaccess data exists, then do bulk insert for internetaccess data.
	    if(datajson.internetaccess){
		    bulkInsertInternetHistoryData(appid,mobileid,datajson.internetaccess,function(err,result){
		    	if(err){
					logger.error(`error is => ${err}`);
		    	}
	    	});				
		}
		//Check if applicationaccess data exists, then do bulk insert for applicationaccess data.
		if(datajson.applicationaccess){
			bulkInsertApplicationAccessData(appid,mobileid,datajson.applicationaccess,function(err,result){
		    	if(err){
					logger.error(`error is => ${err}`);
		    	}
	    	});
		}
		//Check if locations data exists, then do bulk insert for locations data.
		if(datajson.locations){
			bulkInsertLocationData(appid,mobileid,datajson.locations,function(err,result){
	    		if(err){
					logger.error(`error is => ${err}`);
	    		}
	    	});
		}
		//Check if network data exists, then do bulk insert for network data.
		if(datajson.network){
			bulkInsertNetworkData(appid,mobileid,datajson.network,function(err,result){
		    	if(err){
					logger.error(`error is => ${err}`);	 
		    	}
	    	});
		}
		//Check if batterydata data exists, then do bulk insert for batterydata data.
		if(datajson.batterydata){
			bulkInsertBatteryData(appid,mobileid,datajson.batterydata,function(err,result){
		    	if(err){
		    		logger.error(`error is => ${err}`); 
		    	}
	    	});
		}
		//Check if sms data exists, then do bulk insert for sms data.
		if(datajson.sms){
			bulkInsertSmsData(appid,mobileid,datajson.sms,function(err,result){
		    	if(err){
					logger.error(`error is => ${err}`);
		    	}
	    	});
		}
		//Check if emails data exists, then do bulk insert for emails data.
		if(datajson.emails){
			bulkInsertEmailData(appid,mobileid,datajson.emails,function(err,result){
		    	if(err){
		    		logger.error(`error is => ${err}`); 
		    	}
	    	});	
		}
		//Check if appusagedata data exists, then do bulk insert for appusagedata data.
		if(datajson.appusagedata){
			bulkInsertAppusageData(appid,mobileid,datajson.appusagedata,function(err,result){
		    	if(err){
		    		logger.error(`error is => ${err}`); 
		    	}
	    	});	
		}
		//Check if places data exists, then do bulk insert for places data.
		if(datajson.places){
			bulkInsertPlacesData(appid,mobileid,datajson.places,function(err,result){
		    	if(err){
		    		logger.error(`error is => ${err}`); 
		    	}
	    	});
			//Places data contains wifi data as well, so fire bulk insert for wifi data as well.
	    	bulkInsertWifiData(appid,mobileid,datajson.places,function (err,result){
				if(err){
					logger.error(`error is => ${err}`);
				}
			});	
		}
		//Check if error data exists, then do bulk insert for error data.
		if(datajson.error){
			bulkInsertErrorData(appid,mobileid,datajson.error,function(err,result){
				if(err){
					logger.error(`error is => ${err}`);
				}
			});
		}
	};

	//This function does a bulk insert to wifidata table.
	//placesData is an array of objects, and each items can have a wifi object array.
	function bulkInsertWifiData(appid,mobileid,placesData,callback){
		var sql = "INSERT INTO wifidata(appid,deviceid,bssid,timestmp,freq,level,ssid,isprocessed,isconnected) VALUES ?";
		var values=[];
		for (x=0;x<placesData.length;x++){
			//Get wifi array object from placesData item
			var wifiData = (placesData[x].wifi!==undefined) ? placesData[x].wifi:[];
			for(i=0;i<wifiData.length;i++){
				if(wifiData[i].isconnected){
					isconnected = wifiData[i].isconnected;
				}
				else{
					isconnected = 0;
				}
				values.push([appid,mobileid,wifiData[i].bssid,wifiData[i].timestmp,wifiData[i].freq,wifiData[i].level,wifiData[i].ssid,0,isconnected]);
			}	
		}
		
		//Submit bulk query to db.
		if(values.length>0){
			submitBulkQueryToDb(sql,values,function(err,result){
				if(err){
					logger.error(`error is => ${err}`);
				}
			});	
		}
	}

	//This function does a bulk insert to wifidata table.
	//wifiData is an array of objects, and each items can have a wifi object array.
	function bulkInsertWifiDataRoot(appid,mobileid,wifiData,callback){
		var sql = "INSERT INTO wifidata(appid,deviceid,bssid,timestmp,freq,level,ssid,isprocessed,isconnected) VALUES ?";
		var values=[];
		for(i=0;i<wifiData.length;i++){
			if(wifiData[i].isconnected){
				isconnected = wifiData[i].isconnected;
			}
			else{
				isconnected = 0;
			}
			values.push([appid,mobileid,wifiData[i].bssid,wifiData[i].timestmp,wifiData[i].freq,wifiData[i].level,wifiData[i].ssid,0,isconnected]);
		}	
		
		//Submit bulk query to db.
		if(values.length>0){
			submitBulkQueryToDb(sql,values,function(err,result){
				if(err){
					logger.error(`error is => ${err}`);
				}
			});	
		}
	}

	//This function inserts data to browserhistory table.
	//internetAccessData is an object array.
	function bulkInsertInternetHistoryData(appid,mobileid,internetAccessData,callback){
		var sql = "INSERT INTO browserhistory (appid,url,urlcounter,deviceid,CreateDate,Category,BrowseTime) VALUES ?";
		var values=[];
		for(i=0;i<internetAccessData.length;i++){
			if(internetAccessData[i].last && internetAccessData[i].last!=='' && (internetAccessData[i].last!=='0' || internetAccessData[i].last!==0)){
				lastdate = internetAccessData[i].last;	
				lastdate = common.getEpochToDate(lastdate);						
			}
			else{
				lastdate = null;
			}	
			values.push([appid,internetAccessData[i].url,internetAccessData[i].urlcounter,mobileid,moment().format('YYYY-MM-DD HH:mm:ss'),null,lastdate]);
		}	
		
		//Submit bulk query to db.
		if(values.length>0){
			submitBulkQueryToDb(sql,values,function(err,result){
				if(err){
					logger.error(`error is => ${err}`);
				}
			});	
		}
	}

	//This function inserts data to applicationaccess table.
	//applicationAccessData is an object array.
	function bulkInsertApplicationAccessData(appid,mobileid,applicationAccessData,callback){
		var sql = "INSERT INTO applicationaccess (appid,applicationpackage,applicationcounter,deviceid,CreateDate,appname,ResolvedCategory,status,EventDate,type) VALUES ?";
		var values=[];
		for(i=0;i<applicationAccessData.length;i++){
			var type = 'U';
			if(applicationAccessData[i].type){
	   			type = applicationAccessData[i].type;
	   		}	
	   		if(applicationAccessData[i].time){
				lastdate = applicationAccessData[i].time;	
				if(lastdate==""){
					lastdate = moment().format('YYYY-MM-DD HH:mm:ss');
				}
				else{
					lastdate = common.getEpochToDateWithTime(parseInt(lastdate));	
				}
				
			}
			else{
				lastdate = moment().format('YYYY-MM-DD HH:mm:ss');
			}			
			values.push([appid,applicationAccessData[i].applicationpackage,applicationAccessData[i].applicationcounter,mobileid,moment().format('YYYY-MM-DD HH:mm:ss'),applicationAccessData[i].appname,null,applicationAccessData[i].state,lastdate,type]);
		}	
		
		//Submit bulk query to db.
		if(values.length>0){
			submitBulkQueryToDb(sql,values,function(err,result){
				if(err){
					logger.error(`error is => ${err}`);
				}
			});	
		}
	}

	//This function inserts data to locationmaster table.
	//locationsData is an object array.
	function bulkInsertLocationData(appid,mobileid,locationsData,callback){
		var sql = "INSERT INTO locationmaster(appid,deviceid,lat,longitude,timestmp,type,provider,isprocessed) VALUES ?";
		var values=[];
		for(i=0;i<locationsData.length;i++){
			values.push([appid,mobileid,locationsData[i].lat,locationsData[i].longitude,locationsData[i].timestmp,locationsData[i].type,locationsData[i].provider,0]);
		}	
		
		//Submit bulk query to db.
		if(values.length>0){
			submitBulkQueryToDb(sql,values,function(err,result){
				if(err){
					logger.error(`error is => ${err}`);
				}
			});	
		}
	}

	//This function inserts data to networkdata table.
	//networkData is an object array.
	function bulkInsertNetworkData(appid,mobileid,networkData,callback){
		var sql = "INSERT INTO networkdata(appid,deviceid,cid,imsi,lac,mcc,mnc,oname,timestmp,`signal`,isprocessed) VALUES ?";
		var values=[];
		for(i=0;i<networkData.length;i++){
			values.push([appid,mobileid,networkData[i].cid,networkData[i].imsi,networkData[i].lac,networkData[i].mcc,networkData[i].mnc,networkData[i].operatorname,networkData[i].timestmp,networkData[i].signal,0]);
		}	
		
		//Submit bulk query to db.
		if(values.length>0){
			submitBulkQueryToDb(sql,values,function(err,result){
				if(err){
					logger.error(`error is => ${err}`);
				}
			});	
		}
	}

	//This function inserts data to batterydata table.
	//batteryData is an object array.
	function bulkInsertBatteryData(appid,mobileid,batteryData,callback){
		var sql = "INSERT INTO batterydata(appid,deviceid,temp,volt,`level`,health,plug,`status`,timestmp)  VALUES ?";
		var values=[];
		for(i=0;i<batteryData.length;i++){
			values.push([appid,mobileid,batteryData[i].temp,batteryData[i].volt,batteryData[i].level,batteryData[i].health,batteryData[i].plug,batteryData[i].status,batteryData[i].timestamp]);
		}	
		
		//Submit bulk query to db.
		if(values.length>0){
			submitBulkQueryToDb(sql,values,function(err,result){
				if(err){
					logger.error(`error is => ${err}`); 
				}
			});	
		}
	}

	//This function inserts data to rawmessages table.
	//smsData is an object array.
	function bulkInsertSmsData(appid,mobileid,smsData,callback){
		var sql = "INSERT INTO rawmessages (appid,deviceid,messageid,messagebody,fromname,fromphoneno,timereceived,mcc,mnc,lac,cid,lat,lon,categorized,gender_categorized,direction) VALUES ?";
		var values=[];
		for(i=0;i<smsData.length;i++){
			var direction = 'n';
			if(smsData[i].direction){
				direction = smsData[i].direction;
			}
			values.push([appid,mobileid,smsData[i].messageid,smsData[i].messagebody,smsData[i].fromname,smsData[i].fromphoneno,smsData[i].timereceived,smsData[i].mcc,smsData[i].mnc,smsData[i].lac,smsData[i].cid,smsData[i].lat,smsData[i].lon,'0','0',direction]);
		}	
		
		//Submit bulk query to db.
		if(values.length>0){
			submitBulkQueryToDb(sql,values,function(err,result){
				if(err){
					logger.error(`error is => ${err}`);
				}
			});	
		}
	}

	//This function inserts data to emailmaster table.
	//emailData is an object array.
	function bulkInsertEmailData(appid,mobileid,emailData,callback){
		var sql = "INSERT IGNORE INTO emailmaster (appid,deviceid,emailid,type) VALUES ?";
		var values=[];
		for(i=0;i<emailData.length;i++){
			values.push([appid,mobileid,emailData[i].emailid,emailData[i].type]);
		}	
		
		//Submit bulk query to db.
		if(values.length>0){
			submitBulkQueryToDb(sql,values,function(err,result){
				if(err){
					logger.error(`error is => ${err}`);
				}
			});	
		}
	}

	//This function inserts data to sessionallapps table.
	//appUsageData is an object array.
	function bulkInsertAppusageData(appid,mobileid,appUsageData,callback){
		var sql = "INSERT IGNORE INTO sessionallapps(appid,deviceid,timestmp,applicationpackage,`usage`,CreateDate,starttime,place)  VALUES ?";
		var values=[];
		var starttime=null;
		var place='NA';
		for(i=0;i<appUsageData.length;i++){
			if(appUsageData[i].starttime){
				starttime = appUsageData[i].starttime;
			}
			if(appUsageData[i].context && appUsageData[i].context.places && appUsageData[i].context.places._t){
				place = appUsageData[i].context.places._t;
			}
			values.push([appid,mobileid,appUsageData[i]['timestamp'],appUsageData[i]['pkg'],appUsageData[i]['usage'] ,moment().format('YYYY-MM-DD HH:mm:ss'),starttime,place]);
		}	
		
		//Submit bulk query to db.
		if(values.length>0){
			submitBulkQueryToDb(sql,values,function(err,result){
				if(err){
					logger.error(`error is => ${err}`);
				}
			});	
		}
	}

	//This function inserts data to dataerror table.
	//errorData is an object array.
	function bulkInsertErrorData(appid,mobileid,errorData,callback){
		var sql = "INSERT IGNORE INTO dataerror(appid,deviceid,errorinfo,type)  VALUES ?";
		var values=[];
		for(i=0;i<errorData.length;i++){
			values.push([appid,mobileid,errorData[i]['info'],errorData[i]['type']]);
		}	
		
		//Submit bulk query to db.
		if(values.length>0){
			submitBulkQueryToDb(sql,values,function(err,result){
				if(err){
					logger.error(`error is => ${err}`);	 
				}
			});	
		}
	}

	//This function inserts data to locationtuples table.
	//placesData is an object array.
	function bulkInsertPlacesData(appid,mobileid,placesData,callback){
		var sql = "INSERT INTO locationtuples(appid,deviceid,lat,longitude,operator,mcc,mnc,lac,cid,`signal`,provider,networktime,gpstime,iptime,type,ip,imsi,networktype) VALUES ?";
		var values=[];
		for(i=0;i<placesData.length;i++){
			values.push([appid,mobileid,checkVal(placesData[i].lat),checkVal(placesData[i].lng),checkVal(placesData[i].operator),checkVal(placesData[i].mcc),checkVal(placesData[i].mnc),checkVal(placesData[i].lac),checkVal(placesData[i].cid),checkVal(placesData[i].signal),checkVal(placesData[i].provider), checkVal(placesData[i].networktime),checkVal(placesData[i].gpstime),checkVal(placesData[i].iptime),checkVal(placesData[i].type),checkVal(placesData[i].ip),checkVal(placesData[i].imsi),checkVal(placesData[i].networktype)]);
		}	
		
		//Submit bulk query to db.
		if(values.length>0){
			submitBulkQueryToDb(sql,values,function(err,result){
				if(err){
					logger.error(`error is => ${err}`);
				}
			});	
		}
	}

	//This function finally submits the bulk query to database.
	function submitBulkQueryToDb(sql,values,callback){	
		common.mysqldbPool.getConnection(function(err,connection){
	        if (err) {
				logger.error(`error is => ${err}`);
	          connection.release();				          
	          callback('error','');
	        }   
	        connection.query(sql,[values],function(err,result){
	            connection.release();
	            if(!err) {
	                
	               callback('','success');
	            }           
	        });
	        /*connection.on('error', function(err) {    
                      connection.release();
                  callback('error','');
            });*/
	    });
	}

	//This function returns 0, if places data does not exist for a given attribute.
	function checkVal(deviceVal){
		if(deviceVal){
			return deviceVal;
		}
		else{
			return 0;
		}
	}
	
}(backup));

module.exports = backup;