let mmdbreader = require('maxmind-db-reader');
let ip2loc = require("ip2location-nodejs");
let common = require('./common.js');
let logger = require('../../logger');
let request = require('request');

let geoReader = mmdbreader.openSync(__dirname + '/geoip/GeoIP2-City.mmdb');
ip2loc.IP2Location_init(__dirname + '/IP2LOCATION-LITE-DB11/IP2LOCATION-LITE-DB11.BIN');

//users = db.app_users57a07788fbe6532224387e57.find({cty:"Ashburn"});
let counter = 0;
let tempArr = [];
let resCounter = 0;
//{$or:[{cty:""},{cty:""}]}

common.db.collection('app_users575ad5a107db22ae4c3d6cb7').find({$or:[{cc:"--"}]}).toArray(function(err,result){
	if(!err){
		if(result.length > 0){
            getLocation(result, resCounter);
			
            /*result.forEach(function(item){
				let params = {
                    ip_address:item.history[0].ip_address,
					cc:'',
					country:'',
					cty:'',
					region:''
				}                
			    populateLocationUsingMaxmind(params);
                 
			    if(params.cc != 'Unknown' && params.cty != 'Unknown' && params.country != 'Unknown'){
			    	delete params['ip_address'];
                     
                    tempArr.push({params:params, id:item._id});
                     
			    }else{			    	
			    	let params = {
						ip_address:item.history[0].ip_address,
						//ip_address:'128.185.122.207',
						cc:'',
						country:'',
						cty:'',
						region:''
					}
					populateLocationUsingIP2Location(params)
					delete params['ip_address'];
					tempArr.push({params:params, id:item._id});
                     
			    }
			});

			if(tempArr.length > 0){
				counter = 0;
                 
				//updateCity(counter);
			}	*/	
		}
	}
})

function getLocation(result, resCounter){
    if(result[resCounter]){
        let item = result[resCounter];
        let params = {
                    cc:'NA',
                    country:'NA'
                }

        if(item.history[0].ip_address != '127.0.1.1'){
            //url = 'http://freegeoip.net/json/' + item.history[0].ip_address
            url = 'http://api.eurekapi.com/iplocation/v1.8/locateip?key=SAKB9K9573LJW872VBYZ&ip='+item.history[0].ip_address+'&format=JSON';
            request(url, function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    let data = JSON.parse(body);
                     
                    if(data.query_status.query_status_code == 'OK'){
                        params.cc = (data.geolocation_data.country_code_iso3166alpha2 != '' && data.geolocation_data.country_code_iso3166alpha2 != '-')? data.geolocation_data.country_code_iso3166alpha2 : 'NA';
                        params.country = (data.geolocation_data.country_name != '' && data.geolocation_data.country_name != '-')? data.geolocation_data.country_name : 'NA';
                        logger.info(`got location :: ${params.country}`);
                        tempArr.push({params:params, id:item._id});
                    }
                    else{
                        tempArr.push({params:params, id:item._id});
                    }                                   
                }
                resCounter++;
                getLocation(result, resCounter)
            });
        }
        else{
            tempArr.push({params:params, id:item._id});
            logger.info(`set pre define location :: ${params.country}`);
            resCounter++;
            getLocation(result, resCounter)
        }
    }
    else{
        logger.info(`total:: ${tempArr.length}`);
        if(tempArr.length > 0){
            counter = 0;
            updateCity(counter);
        } 
    }  
}

function updateCity(counter){
	if(tempArr[counter]){
		let params = tempArr[counter].params;
        let id = tempArr[counter].id;
        logger.info(`id:: ${id}`);
		common.db.collection('app_users575ad5a107db22ae4c3d6cb7').update({_id:id},{$set:params},function(err,result){
			if(err){
                logger.error(`error ==>> ${err}`);
			}else{
				//if(result){
				 
					//callback();
				//}
                logger.info(`counter:: ${counter}`); 
			}
			counter++;
			updateCity(counter);
		})	
	}
	else{
        logger.info('done!')
	}	
}
//128.185.122.207
function populateParamsWithLocationData(params){
    if(!populateLocationUsingMaxmind(params)){
        //Fallback to IP2Location db if it failed to fetch data.
        populateLocationUsingIP2Location(params);
    }
}

function populateLocationUsingMaxmind(params) {
    // Location of the user is retrieved using geoip-lite module from her IP address.
    let locationData = {};        
    // get geodata 
    let geodata = geoReader.getGeoDataSync(params.ip_address);
     
    let foundcty = false;
    if(geodata){
        if(geodata.country){
            params.cc = geodata.country.iso_code;
            params.country = geodata.country.names.en;
        }
        else{
        	//populateLocationUsingIP2Location(params.ip_address)
            params.cc = 'Unknown'; 
            params.country = 'Unknown';   
        }

        if(geodata.city){
            params.cty = geodata.city.names.en;
            foundcty=true;
        }
        else{
        	 
        	//populateLocationUsingIP2Location(params.ip_address)
          params.cty = 'Unknown';  
        }
        params.region="";
        /*if(geodata.location){
            params.lat  = geodata.location.latitude;
            params.lng = geodata.location.longitude;
        }
        else{
            params.lat = '';
            params.lng = '';
        }*/
    }
    else{
        params.cc = 'Unknown'; 
        params.country = 'Unknown'; 
        params.cty = 'Unknown'; 
        params.region=""; 
        /*params.lat = '';
        params.lng = '';*/
    } 
     
    return true;       
}

function populateLocationUsingIP2Location (params) {
	 
    let result = ip2loc.IP2Location_get_all(params.ip_address);
    let locationData = {};
     
    
    if(result && result.city ){
        if (result.city=='-' || result.city=='' || result.city.toLowerCase()=='unknown' ){
            return false;
        }
        else{
            if(result.country_short){
                params.cc = result.country_short;
            }
            else{
                params.cc = 'Unknown';   
            }
            if(result.country_long){
                params.country = result.country_long;
            }
            else{
                params.country = 'Unknown';   
            }

            if(result.city){
                params.cty = result.city;
            }
            else{
              params.cty = 'Unknown';  
            }

            if(result.region){
                params.region = result.region;
            }
            else{
                params.region = 'Unknown';  
            }
            
           /* if(result.latitude && result.longitude){
                params.lat = result.latitude;
                params.lng = result.longitude;
            }
            else{
                params.lat = '';
                params.lng = '';
            }*/
            return true;
        }
        
    }
    else{            
        return false;
    }
    
}