
$(function() 
{
	if(!AppModules.requiresAdmin())
		return;
	initTouch();
	new SSLView();
	new MobileMenu();
	$('body').show();
	SEDAPI.showServerTime("#server_time", false);
	setInterval(function() {SEDAPI.showServerTime("#server_time", false);}, 30000);
});


class SSLView {
	constructor(options={}) {
		this.init();
	}
	
	init() {
		this.ssltableheight = getCookieInt(COOKIE_SSL_TABLE_HEIGHT, 300);
		var instance = this;
		
		new ColorMode();
		
		new View('ssldata', {
			mode:2, 
			responsive_width: 0,
			handlers: {
				resize: function(height) {
					instance.sizeSSLDataPanel(height);
				}
			}
		});
		
		var datastr = SEDAPI.construct("get", "sslcerts", "colmodel");
		SEDAPI.call(datastr, this.apiGotSSLCertColumns.bind(this), null);
		
		var ui = new UserInput();
		ui.eventHandler('#menucontrol', this);
		
		setTimeout(function(){instance.resizeApp();}, 150);
		$(window).bind('resize', function() {instance.resizeApp(); setTimeout(function(){instance.resizeApp();}, 150);}).trigger('resize');
	}
	
	apiGotSSLCertColumns(x, jqXHR, textStatus, params) {
		if(x != null) {
			if(x.status == "ok") {
				this.initSSLDataTable(x.colmodel);
			}
		}
	}
	
	apiSavedSSLCertColumns(x, jqXHR, textStatus, params) {
		if(x != null) {
			if(x.status == "ok") {
				console.log(x);
			}
		}
	}
	
	initSSLDataTable(columndata) {
		var instance = this;
		columndata = DataTableView.normalizeColumns(columndata);
		var source = {type: 'ajax', params: {url: SEDAPI.getURL(), data: 'c=grid&t=sslcerts&columns=id,serial,issued_by,issued_to,valid_from'}};
		var footer = [{role:'separator'},{role:'add'},{role:'delete'},{role:'separator'},{role:'edit'},{role:'separator'},{role:'refresh'},{role:'separator'},{role:'copy'},{role:'download'},{role:'separator'},{role:'setup',icon:'column-setup'},{role:'separator'},{role:'schedule',icon:'schedule'}];
		var handlers = {
			colwidth: function(column, width) {
				instance.saveColumnWidth(column, width);
			},
			resize: this.resizeApp.bind(this), 
			select: this.sslDataRowSelected.bind(this), 
			ajaxData: this.tableDataReceived.bind(this),
			role: this.roleHandler.bind(this),
			columns: function(cdata, set=true) {
				// if set = false, configure options.columns
				// if set = true, save the column status
				if(set) {
					instance.saveColumns(cdata);
				}
			},
		};
		new SSLDataTable('ssldatatable', {
			columns:columndata, 
			source:source, 
			parent: 'ssltablewrapper', 
			footer: footer, 
			handlers:handlers, 
			sort: 'valid_from', 
			sortorder: 'desc', 
			columnsort: true,
			count: getCookieInt(COOKIE_ITEMS_PER_PAGE, 250), 
			uidelay: grid_auto_search_delay ? grid_auto_search_delay : 600
		});
	}
	
	saveColumns(cdata) {
		console.log(cdata);
		let user_access_rights = parseInt(user_details['rights']);
		if(bit_test(user_access_rights, ALLOW_UICHANGE_BITPOS)) {
			var colsetup = "";
			for(var i = 0; i < cdata.length; i++) {
				if(cdata[i].name != "domain" && cdata[i].name != "d.domain" && cdata[i].name != "r_h_disp" && cdata[i].name != "d.r_h_disp" && cdata[i].name != "dt_ser_num" && cdata[i].name != "cb") {
					if(colsetup != "")
						colsetup += ";" + cdata[i].name;
					else
						colsetup += cdata[i].name;
				}
			}
			console.log(colsetup);
			var datastr = SEDAPI.construct("set", "sslcerts", "colmodel");
			datastr += "&columns=" + encodeURIComponent(colsetup);
			SEDAPI.call(datastr, this.apiSavedSSLCertColumns.bind(this), null);
		}
	}
	
	apiSavedSSLCertColumns(x, jqXHR, textStatus, params) {
		if(x != null) {
			if(x.status == "ok") {
				console.log('ok');
			}
		}
	}
	
	getSelectedRowsText(maxcount=10) {
		var hosts = "";
		var dt = DataTableView.getTable("ssldatatable");
		if(dt) {
			hosts = dt.getSelected('issued_to').slice(0, maxcount).join(", ");
			var hc = $('.tcb-ssldatatable:checkbox:checked').length;
			if(hc > maxcount) {
				hosts += " and " + (hc-maxcount) + " more certificates.";
			}
		}
		return hosts;
	}
	
	roleHandler(command) {
		if(command == "delete") {
			var dt = DataTableView.getTable("ssldatatable");
			if(dt) {
				var ids = dt.getSelectedIds();
				var hosts = this.getSelectedRowsText();
				var info = "About delete the selected certificates. Are you sure?";
				var msg = "This will affect <i>" + hosts + "</i>";
				PopupPanel.confirmAction({
					title: 'Delete SSL Certificates',
					information: info,
					message: msg,
					data: {ids:ids} ,
					onyes: this.deleteSSLsConfirmed.bind(this)
				});
			}
		}
		else if(command == "edit") {
			var dt = DataTableView.getTable("ssldatatable");
			if(dt) {
				var ids = dt.getSelectedIds();
				var hosts = this.getSelectedRowsText();
				new SSLEdit({}).show(ids, hosts);
			}
		}
		else if(command == "add") {
			new SSLAdd({}).show();
		}
		else if(command == "setup") {
			new SSLColumns({}).show();
		}
		else if(command == "schedule") {
			new SSLSchedule({}).show();
		}
	}
	
	deleteSSLsConfirmed(data) {
		var datastr = SEDAPI.construct("grid", "sslcerts", "del");
		datastr += "&id=" + encodeURIComponent(data.ids.join(","));
		console.log(datastr);
		SEDAPI.call(datastr, this.apiDeletedSSLCerts.bind(this), null);
	}
	
	apiDeletedSSLCerts(x, jqXHR, textStatus, params) {
		if(x != null) {
			if(x.status == "ok") {
				var ssltable = DataTableView.getTable('ssldatatable');
				if(ssltable != undefined) {
					ssltable.reload();
				}
				$('#ssldatawrap').html('<pre></pre>');
			}
		}
	}
	
	saveColumnWidth(name, width) {
		let user_access_rights = parseInt(user_details['rights'])
		if(bit_test(user_access_rights, ALLOW_UICHANGE_BITPOS)) {
			var datastr = SEDAPI.construct("set", "sslcerts", "colmodel");
			datastr += "&column=" + encodeURIComponent(name);
			datastr += "&width=" + encodeURIComponent(width);
			SEDAPI.call(datastr, this.apiSavedSSLCertColumns.bind(this), null);
		}
	}
	
	tableDataReceived(tdata) {
		if(tdata) {
		}
	}
	
	sslDataRowSelected(rowid) {
		var data = DataTableView.getTable('ssldatatable').options.data;
		if(data) {
			for(var i = 0; i < data.length; i++) {
				if(data[i].id == rowid) {
					var datastr = SEDAPI.construct("get", "sslcerts", "row");
					datastr += "&id=" + encodeURIComponent(rowid);
					SEDAPI.call(datastr, this.apiGotSSLRow.bind(this), null);
					break;
				}
			}
		}
	}
	
	apiGotSSLRow(x, jqXHR, textStatus, params) {
		if(x != null) {
			if(x.status == "ok") {
				var ssldata = x.data;
				var stext = JSON.stringify(ssldata, null, 4);
				$('#ssldatawrap').html('<pre>' + stext + '</pre>');
			}
		}
	}
	
	openModule(options) {
		AppModules.open(options.param);
	}
	
	/////////////////////////////////////////////////////////////////////////////////////////
	
	sizeSSLDataPanel(height) {
		this.ssltableheight = height + 10;
		saveCookie(COOKIE_SSL_TABLE_HEIGHT, this.ssltableheight);
		this.resizeApp();
	}
	
	/////////////////////////////////////////////////////////////////////////////////////////

	resizeApp() {
		var wht = $(window).height();
		var tbht = $('#sslview-header').outerHeight(true) + $('#appheader').outerHeight(true);
		wht = (wht < 768) ? 768 : wht;
		$('#ssldata').css('height', wht-tbht-10);
		
		var wd = $(window).width();
		if(wd >= 541 && !$('#menucontrol').is(':visible')) {
			$('#menucontrol').show();
			$('.menu-select').css('background-image', 'url(lib/layouts/colors/light/images/64/menu.png)');
		}
		else if(wd <= 540 && $('#menucontrol').is(':visible')) {
			$('#menucontrol').hide();
			$('.menu-select').css('background-image', 'url(lib/layouts/colors/light/images/64/menu.png)');
		}
		
		var height = $('#content').height();
		// Make sure that the lower pane doesn't disappear in small devices.
		var dtht = 0;
		var ssltable = DataTableView.getTable('ssldatatable');
		if(ssltable != undefined) {
			if(this.ssltableheight > (height-300))
				this.ssltableheight = (height < 480) ? height/2 : height-300;
			ssltable.setHeight(this.ssltableheight);
			dtht = this.ssltableheight;
		}
		height = $('#ssldata').height();
		var hsheight = $('#sstablesplit').outerHeight(true);
		var ddheight = height - hsheight - dtht;
		$('#ssldatawrap').css('height', ddheight);
	}
}

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

