/**
 * LogCollector for Skype 2014 Widget
 * minseok ko
 * using singleton pattern
 * 14. 05. 27
 * for kpi log '14 camera on X12 TV
 */

var LogCollector = (function(){
	var instance;
	function init(){
		////////////private member////////////
		var KPI_Log_Plugin = null;
		var service_Object = {};
		var sky = {};
		var lc = {};
		
		
		
		
		///////////private function////////////
		
		lc.util = {
			getDeviceID : function(){
				var eNetwork = sf.core.plugin("Network"),
				// 1: wired, 0: wireless, -1: no active connection
				nNetworkInterface = 1, // DUID should be extracted with the wired
										// MAC address.
				sMac = eNetwork.GetMAC(nNetworkInterface);
				sDUID = sf.core.plugin("NNavi").GetDUID(sMac);
				alert("[SkypeLogCollector]getDeviceID() return : "+sDUID);
				return sDUID;
			},
			getCurrentTime : function(){
				var time_string = new Date().toFormattedString('Y-m-d@H:i:sT').replace('@', 'T');
				alert("[SkypeLogCollector]getCurrentTime() return : "+time_string);
				return time_string;
			},
			getUID : function(){
				
			}
		}
		
		
		InitServiceObject = function(paramObj, service_name){
			alert("[SkypeLogCollector]InitServiceObject()");
			if(paramObj){
				ParsingAndSetServiceObject(paramObj, service_name);
			}else{
				SetDefaultServiceObject();
			}
			
		}
		SetDefaultServiceObject = function(){
			alert("[SkypeLogCollector]SetDefaultServiceObject()");
			alert("[SkypeLogCollector]Do not set default value, LogCollector will not work");
			
			CloseSEFPlugin();
			KPI_Log_Plugin = null;
			
			//140703 do not default value
			//default values
			/*service_Object.service_name = "14_facerecog";
			service_Object.queue_max = 30;
			service_Object.expiration  = 60;
			service_Object.threshold = 0;
			service_Object.log_level = 5;
			service_Object.url = "https://lcstg1.samsungcloudsolution.net/openapi/log/14_facerecog";
			service_Object.event = new Array();*/
		}
		/**
		 * ParsingAndSetServiceObject()
		 * from xml data
		 * service[i]={
		 * 	name:"ddd",
		 *  url : "dddd",
		 *  queue_max:"111",
		 *  expiration : "111",
		 *  loglevel:"111"
		 *  event : [{name:"ddd", loglevel:"111"}, {name:"ddd", loglevel:"111"}]
		 * }
		 */
		ParsingAndSetServiceObject = function(obj, service_name){
			alert("[SkypeLogCollector]ParsingAndSetServiceObject() : "+service_name);
			var service_list = obj.list.service;
			var service_result = null;
			for(var i=0;i<service_list.length;i++){
				if(service_list[i].name === service_name){
					service_result = service_list[i];
					break;
				}
			}
			if(service_result===null){
				SetDefaultServiceObject();
			}else{
				service_Object.service_name = service_name;
				service_Object.queue_max = service_result.queue_max ? parseInt(service_result.queue_max) : 30;
				service_Object.expiration  = service_result.expiration ? parseInt(service_result.expiration) : 60;
				service_Object.threshold = service_result.threshold ? parseInt(service_result.threshold) : 0;
				service_Object.log_level = service_result.loglevel ? parseInt(service_result.loglevel) : 10;
				service_Object.url = service_result.url || "https://lcstg2.samsungcloudsolution.net/openapi/log/14_facerecog";
				service_Object.event = service_result.event
			}
			alert("***********Parsing result!!************");
			alert("service_name : "+service_Object.service_name);
			alert("queue_max : "+service_Object.queue_max);
			alert("expiration : "+service_Object.expiration);
			alert("threshold : "+service_Object.threshold);
			alert("log_level : "+service_Object.log_level);
			alert("url : "+service_Object.url);
			alert("event : "+service_Object.event);
			alert("***************************************");
			
		}
		
		InitSkypeEventObject = function(paramObj){
			alert("[SkypeLogCollector]InitSkypeEventObject()");
			
			//default values
			sky.model_id = paramObj.modelid;
			sky.countryCode = paramObj.country;
			sky.DUID = lc.util.getDeviceID();
			sky.UID = lc.util.getDeviceID();
			
			sky.WidgetID = PluginAPIMgr.Widget_ID;
			sky.AppVersion = sf.env.getAppVersion(); 
			
			alert("***********Event Object!!************");
			alert("model_id : "+sky.model_id);
			alert("countryCode : "+sky.countryCode);
			alert("DUID : "+sky.DUID);
			alert("UID : "+sky.UID);
			alert("WidgetID : "+sky.WidgetID);
			alert("AppVersion : "+sky.AppVersion);
			alert("***************************************");
			
			
			
		}
		
		/**
		 * @event : array of event list
		 */
		SetEventConfig = function(){
			alert("[SkypeLogCollector]SetEventConfig()");
			if(service_Object.event){
				if(service_Object.event.length>0){		//if array
					for(var i=0;i<service_Object.event.length;i++){
						var name = service_Object.event[i].name;
						var loglevel = service_Object.event[i].loglevel ? parseInt(service_Object.event[i].loglevel) : 10;
						var queue_max = service_Object.event[i].queue_max ? parseInt(service_Object.event[i].queue_max) : 30;
						var expiration = service_Object.expiration ? parseInt(service_Object.expiration) : 60;
						var threshold = service_Object.threshold ? parseInt(service_Object.threshold) : 0;
						AddEventConfInfo(name, queue_max, expiration, threshold, loglevel);
					}
				}else if(typeof service_Object.event === "object"){
						var name = service_Object.event.name;
						var loglevel = service_Object.event.loglevel ? parseInt(service_Object.event.loglevel) : 10;
						var queue_max = service_Object.event.queue_max ? parseInt(service_Object.event.queue_max) : 30;
						var expiration = service_Object.expiration ? parseInt(service_Object.expiration) : 60;
						var threshold = service_Object.threshold ? parseInt(service_Object.threshold) : 0;
						AddEventConfInfo(name, queue_max, expiration, threshold, loglevel);
				}else{
					alert("typoe of service_Object.event error");
					//140703 do not default value
				}
			}
		}
		
		
		
		//////////////////////////////////////Plugin Function///////////////////////////////
		
		/**
		 * GetSEFPlugin()
		 * Open emp & set SEF Plugin  
		 */
		GetSEFPlugin = function(){
			KPI_Log_Plugin = document.getElementById('KPI_Log');
			KPI_Log_Plugin.Open("Logging","1.000","Logging");
		}
		CloseSEFPlugin = function(){
			KPI_Log_Plugin.Close();
		}
		
		/**
		 * SetServiceConfigInfo()
		 * - setting sevice infomation
		 * @param
		 *   service_name(string) : service_name mayne "14_facerecog"
		 * 	 queue_max(number) : the number of queue to flush
		 * 	 expiration(string) : the time of queue to flush
		 * 	 threshold : ???
		 *   log_level(number) : level of log(default 10, max 99)
		 *   url(string) : destination sever of log 
		 */
		SetServiceConfigInfo = function(){
			var result = null;
			alert(service_Object);
			alert(service_Object.service_name);
			//140703 do not default value
			if(service_Object.service_name){
				result = KPI_Log_Plugin.Execute("SetServiceConfInfo",
					service_Object.service_name, service_Object.queue_max, 
					service_Object.expiration, service_Object.threshold, service_Object.log_level, service_Object.url);
				alert("[SkypeLogCollector]SetServiceConfigInfo return  : "+result);
			}else{
				alert("[SkypeLogCollector]There is no service Object");
			}
		};
		
		/*
		 * SetEventHeader()
		 * - set event header (common value of events)
		 * @param
		 *   model_id(string)
		 *   uid
		 *   duid
		 *   countryCode
		 */
		SetEventHeader = function(){
			if(KPI_Log_Plugin !== null){
				var result = KPI_Log_Plugin.Execute("SetEventHeader",
				sky.model_id, sky.UID, sky.DUID, sky.countryCode);
				alert("[SkypeLogCollector]SetEventHeader return  : "+result);
			}else{
				alert("[SkypeLogCollector]plug in is null");
			}
		};
		
		/**
		 * AddEventConfInfo
		 *  - set event infomation
		 * @param
		 *   name(string)
		 *   queue_max(number)
		 *   expriation(number)
		 *   threshold
		 *   log_level(number)
		 */
		AddEventConfInfo = function(name, queue_max, expiration, threshold, log_level){
			if(KPI_Log_Plugin !== null){
				var result = KPI_Log_Plugin.Execute("AddEventConfInfo", name, queue_max, expiration, threshold, log_level);
				alert("[SkypeLogCollector]AddEventConfInfo ["+name+"] return  : "+result);
			}else{
				alert("[SkypeLogCollector]plug in is null");
			}
		}
		
		/**
		 * AddEventLog()
		 *  - add log
		 * @param
		 *   evnet_name
		 *   t
		 *   c
		 *   v
		 *   d
		 */
		AddEventLog = function(event_name, t, c, v, d){
			if(v !== ""){
				v = encodeURI(v);
			}
			if(d !== ""){
				d = encodeURI(d);
			}
			alert("***********AddEventLog!!************");
			alert("event_name : "+event_name);
			alert("t : "+t);
			alert("c : "+c);
			alert("v : "+v);
			alert("d : "+d);
			alert("***************************************");
			if(KPI_Log_Plugin !== null){
				var result = KPI_Log_Plugin.Execute("AddEventLog", event_name, t, c, v, d);
				alert("[SkypeLogCollector]AddEventLog return  : "+result);
			}else{
				alert("[SkypeLogCollector]plug in is null");
			}
		};
		
		
		
		
		
		////////////////////////public function////////////////////////////////////
		//user can call this function only//
		/**
			 * init() 
			 * init log collector, can use xmlObj(TBD)<-LogPolicyConfig.xml
			 * @paramObj : object from window.location.search, it will have model_id, uid, duid, countrycode
			 */
		PublicInit = function(paramObj, xmlObj, service_name){
			alert("[SkypeLogCollector]init()");
			GetSEFPlugin();		//init & open emp
			InitServiceObject(xmlObj, service_name);		//init service config
			SetServiceConfigInfo();		//execute SetServiceConfInfo
			InitSkypeEventObject(paramObj);
			SetEventConfig();			//execute AddEventConfInfo
			SetEventHeader();			//execute SetEventHeader
				
		};
		PublicSendLog = function(event, option){
			if(KPI_Log_Plugin===null){
				alert("[SkypeLogCollector] not initialized yet!");
				return;
			}
			alert("[SkypeLogCollector]sendLog() : "+event);
			AddEventLog(event, lc.util.getCurrentTime(), option.category, 
					sky.WidgetID+"|"+sky.AppVersion, option.description);
		};
		PublicAddLog = function(event,description_value){
			if(KPI_Log_Plugin===null){
				alert("[SkypeLogCollector] not initialized yet!");
				return;
			}
			alert("[SkypeLogCollector]AddLog() : "+event);
			var option = {
				category : "",
				description : ""
			}
			switch(event){
				/*case KPI_EVENT.SIGNIN_WITH_PWD:
					option.category = KPI_EVENT_CATEGORY.SIGNIN_WITH_PWD;
					break;
				case KPI_EVENT.FACERECOG_SIGNIN:
					option.category = KPI_EVENT_CATEGORY.FACERECOG_SIGNIN;
					if(description_value){
						option.description =  "{value="+description_value+"}";
					}
					break;
				case KPI_EVENT.FACERECOG_SIGNIN_WITH_PWD:
					option.category = KPI_EVENT_CATEGORY.FACERECOG_SIGNIN_WITH_PWD;
					if(description_value){
						option.description =  "{value="+description_value+"}";
					}
					break;
				case KPI_EVENT.FACEREGIST_SUCCESS:
					option.category = KPI_EVENT_CATEGORY.FACEREGIST_SUCCESS;
					break;
				case KPI_EVENT.FACEREGIST_FAIL:
					option.category = KPI_EVENT_CATEGORY.FACEREGIST_FAIL;
					break;
				case KPI_EVENT.DELETE_FACE:
					option.category = KPI_EVENT_CATEGORY.DELETE_FACE;
					break;
				case KPI_EVENT.FACE_TRACKING:
					option.category = KPI_EVENT_CATEGORY.FACE_TRACKING;
					if(description_value){
						option.description =  "{value="+description_value+"}";
					}
				break;*/
				case KPI_EVENT.CAM_CHECK:
					option.category = "EV001";
					if(description_value){
						option.description =  "{value="+description_value+"}";
					}
					break;
			}
			PublicSendLog(event,option);
			
		};
		
		PublicDestroy = function(){
			CloseSEFPlugin();
		};
		return {
			init : PublicInit,
			sendLog : PublicSendLog,
			addLog : PublicAddLog,
			destroy : PublicDestroy
		};
	}//end of init()
	
	return {
		getInstance: function () {
 
	      if ( !instance ) {
	        instance = init();
	      }
	 
	      return instance;
	    }
	}
	
	
	
	
	
	////////////////////////////////////////////for convert date format	////////////////////////////////////////////////////
	/**
	 * reference from Camera App. logcollector.js
	 */
	
	Date._MonthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];
	Date._MonthNames_abbr = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ];
	Date._DayNames = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
	Date._DayNames_abbr = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ];

	// Overrides of Date class
	Date.prototype.toFormattedString = function(formatStr) {
		if (!formatStr) {
			formatStr = Date.getLocaleFormatStr();
		}
		if (!formatStr) {
			formatStr = 'm/d/Y h:i a';
		}

		var _THIS_ = this;
		var aDaysInMonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

		var str = (formatStr + '').replace(/(d|D|j|l|N|S|w|z|F|m|M|n|t|Y|y|a|A|g|G|h|H|i|s|u|T)/g, function($1) {
			switch ($1) {
			// Day
			case 'd':
				return addZero(_THIS_.getDate(), 2);
			case 'D':
				return Date._DayNames_abbr[_THIS_.getDay()];
			case 'j':
				return _THIS_.getDate();
			case 'l':
				return Date._DayNames[_THIS_.getDay()];
			case 'S':
				return addTh(_THIS_.getDate());
			case 'w':
				return _THIS_.getDay();

				// Month
			case 'F':
				return Date._MonthNames[_THIS_.getMonth()];
			case 'm':
				return addZero(_THIS_.getMonth() + 1, 2);
			case 'M':
				return Date._MonthNames_abbr[_THIS_.getMonth()];
			case 'n':
				return (_THIS_.getMonth() + 1);
			case 't':
				return aDaysInMonth[_THIS_.getMonth()]
						+ (_THIS_.getFullYear() % 4 == 0 && _THIS_.getFullYear() % 100 != 0 || _THIS_.getFullYear() % 400 == 0)
						&& _THIS_.getMonth() == 1 ? 1 : 0;

				// Year
			case 'Y':
				return _THIS_.getFullYear();
			case 'y':
				return (_THIS_.getFullYear() + '').substr(2, 2);

				// Time
			case 'a':
				return _THIS_.getHours() < 12 ? 'am' : 'pm';
			case 'A':
				return _THIS_.getHours() < 12 ? 'AM' : 'PM';
			case 'g':
				return _THIS_.getHours() % 12;
			case 'G':
				return _THIS_.getHours();
			case 'h':
				return addZero((_THIS_.getHours() % 12) || 12, 2);
			case 'H':
				return addZero(_THIS_.getHours(), 2);
			case 'i':
				return addZero(_THIS_.getMinutes(), 2);
			case 's':
				return addZero(_THIS_.getSeconds(), 2);
			case 'u':
				return _THIS_.getMilliseconds();

				// Time Zone
			case 'T':
				var diff = _THIS_.getTimezoneOffset() / 60; // if the timezone
															// is -5, diff is 5
				var plus = diff <= 0 ? '+' : '-';
				diff = Math.abs(diff);
				var diffHour = Math.floor(diff);
				var diffMin = (diff - diffHour) * 60;
				diffHour = (diffHour < 10 ? '0' : '') + diffHour;
				diffMin = (diffMin < 10 ? '0' : '') + diffMin;
				return plus + diffHour + ':' + diffMin;
			}
			return '';
		});

		return str;

		function addZero(str, length) {
			str += '';
			for ( var i = 0; str.length < length; i++)
				str = '0' + str;
			return str;
		}

		function addTh(num) {
			var endnum = num - parseInt(num / 10, 10) * 10;
			var str = num + '' + (endnum == 1 ? 'st' : endnum == 2 ? 'nd' : endnum == 3 ? 'rd' : 'th');
			return str;
		}
	}

	// d/m/Y a h:i
	// d/m/Y a H:i
	var localeTimeFormats = {
		1 : 'Y/m/d a h:i', // KR - \uad6d\ud310 - YYYY/MM/DD am(pm) HH:MM (\uc0ac\uc591)
		2 : 'm/d/Y h:i a', // US - \ubbf8\uc8fc - MM/DD/YYYY HH : MM am(pm) (\uc0ac\uc591)
		3 : 'd/m/Y h:i a', // BR - \uc911\ub0a8\ubbf8(\ube0c\ub77c\uc9c8,\uc544\ub974\ud5e8,\uce60\ub808,\uc6b0\ub8e8\uacfc\uc774,\ud30c\ub77c\uacfc\uc774,\uc5d0\ucf70\ub3c4\ub974\ub4f1) - DD/MM/YYYY
							// HH : MM am(pm) (\uc0ac\uc591)
		4 : 'd/m/Y H:i', // PANEURO - \uad6c\uc8fc - DD/MM/YYYY 24HH : MM (\uc0ac\uc591)
		5 : 'd/m/Y h:i a', // CHI - \uc911\uad6d - DD/MM/YYYY HH : MM am(pm) (\uc0ac\uc591)
		6 : 'd/m/Y h:i a', // HKG - \ud64d\ucf69 - DD/MM/YYYY HH : MM am(pm) (\uc0ac\uc591)
		7 : 'd/m/Y h:i a', // ARB - ? - DD/MM/YYYY HH : MM am(pm)
							// (\ud655\uc778From\ubc30\uc2dc\ubbc0\uc628K:\uad6c\uc8fc\ub0a0\uc9dc\uc0ac\uc591)
		8 : 'd/m/Y H:i', // PANNORDIG - \uad6c\uc8fc - DD/MM/YYYY 24HH : MM (\uc0ac\uc591)
		9 : 'd/m/Y h:i a', // SOUTHEASTASIA - ? - DD/MM/YYYY HH : MM am(pm)
							// (\ud655\uc778From\ubc30\uc2dc\ubbc0\uc628K:\uad6c\uc8fc\ub0a0\uc9dc\uc0ac\uc591)
		10 : 'd/m/Y h:i a', // ASIA_ATV - ? - DD/MM/YYYY HH : MM am(pm)
							// (\ud655\uc778From\ubc30\uc2dc\ubbc0\uc628K:\uad6c\uc8fc\ub0a0\uc9dc\uc0ac\uc591)
		11 : 'd/m/Y h:i a', // ASIA_DTV - ? - DD/MM/YYYY HH : MM am(pm)
							// (\ud655\uc778From\ubc30\uc2dc\ubbc0\uc628K:\uad6c\uc8fc\ub0a0\uc9dc\uc0ac\uc591)
		12 : 'd/m/Y h:i a', // TW - \ub300\ub9cc/\ud30c\ub098\ub9c8 - DD/MM/YYYY HH : MM am(pm) (\uc0ac\uc591)
		13 : 'd/m/Y h:i a', // NORTHAFRICA - ? - DD/MM/YYYY HH : MM am(pm)
							// (\ud655\uc778From\ubc30\uc2dc\ubbc0\uc628K:\uad6c\uc8fc\ub0a0\uc9dc\uc0ac\uc591)
		14 : 'd/m/Y h:i a', // EA_DTV - ? - DD/MM/YYYY HH : MM am(pm)
							// (\ud655\uc778From\ubc30\uc2dc\ubbc0\uc628K:\uad6c\uc8fc\ub0a0\uc9dc\uc0ac\uc591)
		15 : 'd/m/Y h:i a', // CIS - \uc131\uc7a5 - DD/MM/YYYY HH : MM am(pm)
							// (\ud655\uc778From\ubc30\uc2dc\ubbc0\uc628K:\uad6c\uc8fc\ub0a0\uc9dc\uc0ac\uc591)
		16 : 'd/m/Y h:i a', // PHI - \ud544\ub9ac\ud540? - DD/MM/YYYY HH : MM am(pm)
							// (\ud655\uc778From\ubc30\uc2dc\ubbc0\uc628K:\uad6c\uc8fc\ub0a0\uc9dc\uc0ac\uc591)
		17 : 'd/m/Y h:i a', // S_AFR_DTV - \ub0a8\uc544\uacf5? - DD/MM/YYYY HH : MM am(pm)
		0 : null, // UNKNOWN - \uae30\ubcf8\uc124\uc815:\ubbf8\uc8fc - MM/DD/YYYY HH : MM am(pm) (\uc0ac\uc591)
	}
	var targetLoc = null;
	Date.getLocaleFormatStr = function() {
		if (!targetLoc) {
			targetLoc = sf.env.getTargetLocation();
		}
		return localeTimeFormats[targetLoc] || localeTimeFormats[2];
	}

	Number.prototype.addZeros = function(length) {
		var str = this + '';
		for ( var i = 0; str.length < length; i++)
			str = '0' + str;
		return str;
	}

	Number.prototype.addTh = function() {
		var str = this + '' + (this <= 1 ? 'st' : this == 2 ? 'nd' : this == 3 ? 'rd' : 'th');
		return str;
	}

	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g, "");
	}
	
})();


	