var mixpanelDataExport={},
	moment = require('moment-timezone'),
	deviceImport = require('./../utils/common.deviceimport.js'),
	common = require('./../utils/common.js'),
	dataConsumer = require('./../utils/common.data.consumer.js'),
	async = require('async'),
	fs = require('fs');
	FileQueue = require('filequeue');
	semusiConfig = require('../config')


(function (mixpanelDataExport) {


var APPID = "568f467165dcb37d16000004";//"5704dd2011c745ab1e28cc95";//;
var APPKEY = "52e590931979319e46761662dee62934b6a4ab1b";//"e4389d82d606884dddd14fda8942210829063a26";//;
var APIKEY = "d985715d1bb48942d36d5d08de3b6a8c";

readFiles('/Users/sapinder/Projects/MixPanel/');
//var date = new Date('नवम्बर 10,2015 12:31');
//var date = new Date("2015-10-31T18:53:00");
 
 


var index = 0;
var totalFiles = 0;
var files=[];
var fq = new FileQueue(200);
function readFiles(dirname) {
	fs.readdir(dirname, function(err, filenames) {
		if (err) {
		  	 
		}
		totalFiles = filenames.length;
		files = filenames;
		//processFile();
		processEventsFile();

	});
}

function processFile(){
	if(index>=totalFiles){
		 
		 
		return;
	}
	var filename = files[index];
	var jsonContent;
	 
	if(filename.indexOf("people19")>=0){		
		fq.readFile('/Users/sapinder/Projects/MixPanel/'+filename,function(err,contents){
			if(err){
				 
			}
			else{
				try{
					jsonContent = JSON.parse(contents);
					if(jsonContent.results && jsonContent.results.length>0){
						 
						async.forEach(jsonContent.results, function(item, callback){							
							var appUser = createAppUserObject_Android(item);						
							 
							if(appUser!==undefined){
								deviceImport.registerDevice(appUser,function(response){
									if(response.statusCode!=200){
										 
									}						
									callback();					
								});	
							}
							else{
								callback();
							}						
							
						},function(error){
							if (error){
								 
								
							}else{
								 
								index++;
								processFile();
								
							}
						});
					}
				}
				catch(e){
					 
					index++;
					processFile();								
				}
				
			}
		});			
			
	}
	else{
		index++;
		processFile();
	}
	
}

function processEventsFile(){
	if(index>=totalFiles){
		 
		 
		return;
	}
	var filename = files[index];
	var jsonContent;
	 
	if(filename.indexOf("events1_")>=0){		
		fq.readFile('/Users/sapinder/Projects/MixPanel/'+filename,function(err,contents){
			if(err){
				 
			}
			else{
				try{
					jsonContent = JSON.parse(contents);
					 
					if(jsonContent && jsonContent.length>0){
						 
						var events = [];
						var groupedEvents =[];
						jsonContent.forEach(function(item){
							var obj = createEventObject(item);
							if(obj){
								 
								events.push(obj);
								if(events.length==1000){
									groupedEvents.push({events:events});
									events=[];
								}
							}
						});
						if(events.length>0){
							groupedEvents.push({events:events});											
						}
						async.forEach(groupedEvents, function(item, callback){							
							var obj = {
								appid:APPID,
								dataArray:item
							}
							dataConsumer.processEvents(obj,function(status){
								callback();
							});
							
						},function(error){
							if (error){
								 
								
							}else{
								 
								index++;
								processEventsFile();
								
							}
						});
						index++;
						processEventsFile();
					}
				}
				catch(e){
					 
					index++;
					processEventsFile();								
				}
				
			}
		});			
			
	}
	else{
		index++;
		processEventsFile();
	}
	
}

function createAppUserObject_Android(user){
	var appUser = {};	
	appUser.app_id = APPID;
	appUser.app_key = APPKEY;
	appUser.api_key = APIKEY;
				
	if(user['$distinct_id']){
		appUser.device_id = user['$distinct_id']; 
	}
	if(user['$properties']){
		var data = user['$properties'];
		var keys = Object.keys(data);
		appUser.metrics={
			"_locale":"en_US",
			"_ref":"Mixpanel",																						
			"context":{"where" : {"location" : {"place" : "other"},"geo" : {}}},									
			"_installer":"Mixpanel"
		};
		appUser.moreInfo={};
		if(keys.length>0){
			keys.forEach(function(key){								
				switch(key){
					case "$android_app_version":{
						appUser.metrics['_app_version'] = data[key];
						break;
					}
					case "$android_manufacturer":
					case "$android_model":{
						var device ="";
						var manufacturer = (data['$android_manufacturer'])? data['$android_manufacturer']+" ":"";
						var model = (data['$android_model'])? data['$android_model']:"";
						if(model && typeof(model)=='string' && model.indexOf(manufacturer)==0){
							device = model;
						}
						else{
							device = manufacturer+model;
						}						
						appUser.metrics['_device'] = device;
						break;
					}
					case "$android_os_version":{
						appUser.metrics['_os_version'] = data[key];
						break;
					}
					case "$android_os":{
						appUser.metrics['_os'] = data[key];
						break;
					}										
					case "$android_app_version_code":{
						appUser.metrics['_app_code'] = data[key];
						break;
					}					
					case "UserCreatedAt":{
						if(data['$timezone']){							
							if(new Date(data[key])!== "Invalid Date"){
								var tz = moment(data[key]).tz(data['$timezone'])._offset*60;								
								appUser.metrics['_tz']=tz;
								 
								if(isNaN(tz)){
									appUser.timestamp=undefined;
								}
								else{										
									appUser.timestamp = (moment(data[key]).valueOf()/1000)-tz;
									appUser.inittime = appUser.timestamp;	
								}	
							}
							else{
								appUser.timestamp=undefined;
							}																	
						}											
						break;
					}
					case "$android_devices":{
						if(data[key].length>0){
							appUser.moreInfo['gcmid'] = data[key][0];	
						}						
						break;
					}
					case "$region":{
						appUser.moreInfo['region'] = data[key]
						break;
					}
					case "$city":{
						appUser.moreInfo['cty'] = data[key];
						break;
					}
					case "$country_code":{
						appUser.moreInfo['cc'] = data[key];
						appUser.moreInfo['country'] = data[key];
						break;
					}
					case "$last_seen":{
						if(appUser.metrics['_tz']){
							appUser.moreInfo['ls'] = (moment(data[key]).valueOf()/1000)-appUser.metrics['_tz'];	
						}
						
						//If last seen less than created date then set last seen to created date.
						if(appUser.moreInfo['ls'] && appUser.timestamp){
							if(appUser.timestamp>appUser.moreInfo['ls']){
								appUser.moreInfo['ls'] = appUser.timestamp;
							}
						}
						break;
					}
					case "$name":{
						appUser.moreInfo['_custom_Name'] = data[key].replace("&","");
						break;
					}
					case "$email":{
						appUser.moreInfo['_custom_Email'] = data[key];
						break;
					}
					case "$predict_grade":{
						appUser.moreInfo['_custom_Grade'] = data[key];
						break;
					}
					case "$unsubscribed":{
						appUser.moreInfo['_custom_Unsubscribed'] = data[key];
						break;
					}
					case "LastSeenPage":{
						appUser.moreInfo['le'] = {"k":data[key],"t":appUser.timestamp};
					}
				}
			});		
		}	
	}
	if(appUser.timestamp===undefined){
		 
		var log = fs.createWriteStream("missingcreatedate.json", {'flags': 'a'});    	
    	log.end(JSON.stringify(data,null,4)+",");

		return undefined;
	}

	appUser.metrics = JSON.stringify(appUser.metrics);
	appUser.moreInfo = JSON.stringify(appUser.moreInfo);

	return appUser;

}


function createEventObject(eventData){
	var eventObj={};
	var context = {
		who:{device:{}},
		what:{},
		where:{location:{place:"other"},geo:{}},
		when:{}
	};
	var segmentation={};
	
	if(eventData['event']){		
		eventObj.key = eventData['event']
		if(eventObj.key.indexOf("$")==0){
			return undefined;
		}
	}
	var data = eventData['properties'];
	var keys = Object.keys(data);
	keys.forEach(function(key){
		switch(key)	{
			case "time":{
				eventObj.eventTime = data[key];
				break;
			}
			case "distinct_id":{
				eventObj.did = data[key];
				eventObj.user_id = common.crypto.createHash(semusiConfig.shaV1Hash).update(APPKEY + data[key] + "").digest('hex');
				break;
			}
			case "$app_version":{
				context.who.device.av=data[key];
				break;
			}
			case "$carrier":{
				context.who.device.c=data[key];
				break;
			}
			case "$city":{
				context.where.geo.cty=data[key];
				break;
			}
			case "$manufacturer":
			case "$model":{
				var device ="";
				var manufacturer = (data['$manufacturer'])? data['$manufacturer']+" ":"";
				var model = (data['$model'])? data['$model']:"";
				if(model && typeof(model)=='string' && model.indexOf(manufacturer)==0){
					device = model;
				}
				else{
					device = manufacturer+model;
				}
				context.who.device.d=device;		
				break;
			}
			case "$os":{
				context.who.device.p=data[key];
				break;
			}
			case "$os_version":{
				context.who.device.pv=data[key];
				break;
			}
			case "$screen_height":
			case "$screen_width":{
				var width = (data["$screen_width"])?data["$screen_width"]:"";
				var height = (data["$screen_height"])?data["$screen_height"]:"";
				context.who.device.r = width+"x"+height;
				break;
			}
			case "mp_country_code":{
				context.where.geo.cc=data[key];
				break;
			}
			case "$region":{
				context.where.geo.region=data[key];
				break;
			}
			case "mp_lib":
			case "$wifi":
			case "$lib_version":
			case "$has_telephone":
			case "$has_nfc":
			case "$google_play_services":
			case "$experiments":
			case "$bluetooth_version":
			case "$bluetooth_enabled":
			case "$brand":
			case "Model Brand":
			case "Model Name":{

				break;
			}
			default:{
				//Create event segmentation here.
				if(typeof(data[key])==='string' && data[key].indexOf('$')!==0 ){
					segmentation[key] = data[key];
				}				
				break;
			}
		}
	});
	
	eventObj.context = context;	
	if(Object.keys(segmentation).length>0){        
        eventObj.attributes = createSegmentCopy(segmentation);
        eventObj.segment = segmentation;            
	}
	
	if(eventObj.key==undefined){
		return undefined;
	}

	return eventObj;
}

function createSegmentCopy(segment){
	var keys = Object.keys(segment);
	var obj={};
	keys.forEach(function(key){
		if(typeof(segment[key])=='string'){
			obj[key] = segment[key].toLowerCase();
		}
		else{
			obj[key] = segment[key];
		}
	});

	return obj;
}

 
}(mixpanelDataExport));

module.exports = mixpanelDataExport;