var customObj = {},
    common = require('./../../utils/common.js'),
    logger = require('../../../logger'),
    mmdbreader = require('maxmind-db-reader'),
    semusiConfig = require('./../../config'),
    AWS = require('aws-sdk'),
    async = require('async'),
    ip2loc = require("ip2location-nodejs");

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

function getUsers(appid){
    //var  ctyList = ['Mountain View','Palatine','Singapore','As Sib','Auckland','Ottawa','Goma','San Jose','Toronto','Laval','Mykolayiv','Dallas','Ōita','Hong Kong','Matawan','Al Mahbulah','Roosendaal','Tokyo','Riga','Khobar','Yen Bai','Leeds','Dubai','Bata','Ryde','Bucharest','New York','Guangzhou','Nairobi','Tseung Kwan O','Paris','Amsterdam','London','San Mateo','Chelmsford','Rome','Muscat','Victoria','Damascus','Abu Dhabi','New York City','Durham','Montreal','Dammam','Jakarta','Gdańsk','Baldwin Park','Roubaix','Riyadh','Aalborg','Los Angeles','Woodbridge','Frankfurt am Main','San Francisco','Manassas','Zurich','Habbouch','Gloucester','Detroit','Berlin','Dhaka','Beijing','Rosedale','Nokia','Houston','Absecon','Roseland','Irving','Palo Alto','Wilmington','Bandar Seri Begawan','Steinsel','Ar Rifa','Encinitas','Sacramento','Fremont','Central District','Downers Grove','Burbank','Shanghai','Boardman','Lalitpur','Nyborg','Munich','Preston','Hilden','Torrance','Suva','Medina','Kuala Lumpur','Kathmandu','Atlanta','Sofia','At Tuwal','Abu','Arish','Oslo','Al Jizah','Chattanooga','Richmond','Kabul','Kwai Chung','Hanoi','Dar es Salaam','Omiya','Harrow','Kuwait City','Bawshar','Lewes','Secaucus'];
    // 'cty':{$in:ctyList}
    common.db.collection('app_users'+appid).find({},{history:1, cty:1}).toArray(function(err,result){
        var counter = 1;
        async.each(result,function (user, callback){
            if(user){
                if(user.history){
                    if(user.history[0]){
                        var params = {};
                        params.user = {};
                        params.ip_address = user.history[0].ip_address;
                        populateParamsWithLocationData(params);
                         

                        if(params.user){
                            var isupdate = true;
                            var setObj = {};
                            // set city
                            if(params.user.city){
                                setObj.cty = params.user.city;
                            }
                            else if(params.user.city == undefined || params.user.city == ''){
                                isupdate = false;
                            }

                            // set country code
                            if(params.user.cc){
                                setObj.cc = params.user.cc;
                            }
                            else if(params.user.cc == undefined || params.user.cc == ''){
                                isupdate = false;
                            }

                            // set country
                            if(params.user.country){
                                setObj.country = params.user.country;
                            }
                            else if(params.user.country == undefined || params.user.country == ''){
                                isupdate = false;
                            }

                            // set region
                            setObj.region = (params.user.region)? params.user.region : '';

                             
                            // update app user information
                            if(isupdate){
                                common.db.collection('app_users'+appid).update({_id:user._id},{$set:setObj}, {multi:true}, function (err, res) {
                                    if(err){
                                        logger.error(`update error => ${err}`);  
                                    }
                                    else{
                                        logger.info(`user id : ${user._id} update res success: ${res}`);  
                                    }
                                    logger.info(`counter: ${counter}`);
                                    counter++;
                                    callback();
                                });
                            }
                            else{
                                callback();
                            }
                        }
                    }
                    else{
                        callback();
                    }
                }
                else{
                    callback();
                }
            }
            else{
                callback();
            }
        }, function(err, data){
                if(err){
                    logger.error(`error: ${err}`);    
                }
                else{
                    logger.info(`success`);
                    //process.exit(0);
                }
            }
        )
    });
}

getUsers('5ad83ce1f71de7016db4c0c1');

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.
    var locationData = {};
    // get geodata
    var geodata = geoReader.getGeoDataSync(params.ip_address);
    var foundCity = false;
    if(geodata){
        if(geodata.country){
            params.user.cc = geodata.country.iso_code;
            params.user.country = geodata.country.names.en;
        }
        else{
            params.user.cc = 'Unknown';
            params.user.country = 'Unknown';
        }

        if(geodata.city){
            params.user.city = geodata.city.names.en;
            foundCity=true;
        }
        else{
            params.user.city = 'Unknown';
        }
        params.user.region="";
        if(geodata.location){
            params.user.lat  = geodata.location.latitude;
            params.user.lng = geodata.location.longitude;
        }
        else{
            params.user.lat = '';
            params.user.lng = '';
        }
    }
    else{
        params.user.cc = 'Unknown';
        params.user.country = 'Unknown';
        params.user.city = 'Unknown';
        params.user.region="";
        params.user.lat = '';
        params.user.lng = '';
    }

    return foundCity;
}

function populateLocationUsingIP2Location (params) {

    var result = ip2loc.IP2Location_get_all(params.ip_address);
    var locationData = {};
     

    if(result && result.city ){
        if (result.city=='-' || result.city=='' || result.city.toLowerCase()=='unknown' ){
            return false;
        }
        else{
            if(result.country_short){
                params.user.cc = result.country_short;
            }
            else{
                params.user.cc = 'Unknown';
            }
            if(result.country_long){
                params.user.country = result.country_long;
            }
            else{
                params.user.country = 'Unknown';
            }

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

            if(result.region){
                params.user.region = result.region;
            }
            else{
                params.user.region = 'Unknown';
            }

            if(result.latitude && result.longitude){
                params.user.lat = result.latitude;
                params.user.lng = result.longitude;
            }
            else{
                params.user.lat = '';
                params.user.lng = '';
            }
            return true;
        }

    }
    else{
        return false;
    }

}
