class SEDAPI {
	static construct(command, target, oper) {
		var datastr = "";
		if(command != "") {
			datastr += "c=" + encodeURIComponent(command);
			if(target != "")
				datastr += "&t=" + encodeURIComponent(target);
			if(oper != "")
				datastr += "&oper=" + encodeURIComponent(oper);
		}
		return datastr;
	}

	static parse(msg) {
		try {
			var x = jQuery.parseJSON(msg);
			if(typeof x.validate != "undefined") {
				// do session checks only if there is a logged in user
				var usi = (typeof user_details != "undefined" && typeof user_details.uid != "undefined" && user_details.uid >= 0);
				if(usi) {
					if(x.validate == 1)
						SEDAPI.sessionRestart("auth_error_session_timeout");
					else if(x.validate == -1 || x.validate == -2)
						SEDAPI.sessionRestart("notloggedin");
				}
			}
			return x;
		}
		catch(err) {
			console.log('Error: JSON Parser: ' + err);
		}
		return [];
	}
	
	static call(datastr, callbackFn=null, param=null) {
		var request = $.ajax({type: "POST",	url: SEDAPI.getURL(), data: datastr});
		request.done(function(msg) {  
			var x = SEDAPI.parse(msg);
			if(callbackFn)
				callbackFn(x, null, null, param);
		});
		request.fail(function(jqXHR, textStatus) {
			if(callbackFn)
				callbackFn(null, jqXHR, textStatus, param);
		});
	}
	
	static formData(fd, callbackFn=null, param=null) {
		var request = $.ajax({type: "POST",	url: SEDAPI.getURL(), data: fd, contentType: false, processData: false, cache: false});
		request.done(function(msg) {  
			var x = SEDAPI.parse(msg);
			if(callbackFn)
				callbackFn(x, null, null, param);
		});
		request.fail(function(jqXHR, textStatus) {
			if(callbackFn)
				callbackFn(null, jqXHR, textStatus, param);
		});
	}
	
	static sessionRestart(reason) {
		AppModules.logout(reason);
	}
	
	static getURL() {
		return AppModules.getRootURL() + api_url_path;
	}
	
	static showServerTime(elem, swipein=false) {
		var datastr = SEDAPI.construct("get", "time", "") + "&sw=" + (swipein ? "true" : "false");
		SEDAPI.call(datastr, SEDAPI.apiCallBack, {elem: elem, ep: 'showtime'});
	}
	
	static apiCallBack(x, jqXHR, textStatus, params) {
		if(x != null && params != undefined && params.ep != undefined) {
			if(x.status == 'ok') {
				if(params.elem != undefined && params.ep == 'showtime')
					$(params.elem).html(x.server_time);
			}
		}
	}
	
	static saveLicenseCode(code) {
		var datastr = "c=add&t=license&data=" + encodeURIComponent(code);
		SEDAPI.call(datastr, SEDAPI.apiLicenseAdded, null);
	}
	
	static apiLicenseAdded(x, jqXHR, textStatus, params) {
		AppModules.open();
	}
	
	static formatDate(timevalue, formatcode="onlydate", column=null) {
		if(timevalue) {
			const date1 = new Date(timevalue);
			const date2 = new Date();
			const diffTime = date1 - date2;
			const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24)); 
			var v = parseInt(diffDays);
			
			var mv = Math.abs(v)
			var classname = ''
			if(column && (column.indexOf('expiry') >= 0 || column.indexOf('valid_to') >= 0)) {
				if(v < 0)
					classname = 'expired';
				else if(v < 7)
					classname = 'expiring07';
				else if(v < 30)
					classname = 'expiring30';
				else if(v < 45)
					classname = 'expiring45';
				else if(v < 120)
					classname = 'expiring120';
				else if(v < 180)
					classname = 'expiring180';
				else if(v < 365)
					classname = 'expiring365';
				else if(v <= 730)
					classname = 'expiring2y';
				else if(v > 730)
					classname = 'expiring2yplus';
			}
			else if(column && column.indexOf('_checked_at') >= 0) {
				if(mv < 7)
					classname = 'brightgreen';
				else if(mv < 30)
					classname = 'green';
				else if(mv < 60)
					classname = 'lightgreen';
				else if(v < 120)
					classname = 'lightred';
				else if(v < 365)
					classname = 'red';
				else 
					classname = 'brightred';
			}
			else if(column && (column.indexOf('updated') >= 0)) {
				if(mv < 7)
					classname = 'brightred';
				else if(mv < 30)
					classname = 'red';
				else if(mv < 60)
					classname = 'lightred';
				else if(v < 120)
					classname = 'lightgreen';
				else if(v < 365)
					classname = 'green';
				else 
					classname = 'brightgreen';
			}
			else if(column && (column.indexOf('created') >= 0)) {
				if(mv < 365)
					classname = 'brightred';
				else if(mv < 730)
					classname = 'red';
				else if(mv < 1825)
					classname = 'lightred';
				else if(mv < 2920)
					classname = 'lightgreen';
				else if(mv < 3650)
					classname = 'green';
				else 
					classname = 'brightgreen';
			}
			
			if(mv < 100)
				v += 'D'
			else if(mv <= 730) {
				v /= 30
				v = parseInt(v) + 'M';
			}
			else  {
				v /= 365
				v = parseInt(v) + 'Y';
			}	
			
			var nf = formatcode;
			var timestamp = ((nf == "datetime") ? true : false);
			if(nf == "onlydate" || nf == "datetime")
				nf = (default_date_format === undefined) ? "MMM-DD-YYYY" : default_date_format;
			if(nf.includes(' H:i:s') || nf.includes(' hh:mm:ss')) {
				nf = nf.replace(' H:i:s', '').replace(' hh:mm:ss', '');
				timestamp = true;
			}
			var keys = {'Y-M-d': 'YYYY-MMM-DD', 'Y-m-d': 'YYYY-MM-DD', 'd-M-Y': 'DD-MMM-YYYY', 'M-d-Y': 'MMM-DD-YYYY', 'd/M/Y': 'DD/MMM/YYYY', 'M/d/Y': 'MMM/DD/YYYY'};
			if(keys.hasOwnProperty(nf))
				nf = keys[nf];
			else {
				// make sure the format is valid.
				if(!Object.values(keys).includes(nf))
					nf = 'YYYY-MMM-DD';
			}
			if(timestamp)
				nf += ' hh:mm:ss a'
			//return dayjs(timevalue).format(nf);
			return '<span class="' + classname + '">' + v + '</span>&nbsp;<span>' + dayjs(timevalue).format(nf) + '</span>';
		}
		return '';
	}
}

/////////////////////////////////////////////////////////////////////////////////////////
