function Request() {
    var request = {
        url: "",
        parameters: {},
        statusType: "",
		typeNumber: "",
		isSingleStatus:false
    };
    return request;
}
$(window).bind("load", function() {     
	$('#btnSearch').trigger('click',function(){
		return false;
	});
	GetConsoleLogs()
	
});
function GetLogs()
{	
	let  tableHeader = ` <div id="graph-water-mark" style=" width:100%; height:100%;">
	<img class="" src ="../images/loader.gif" style="margin: 50px auto; display:block;"></div>`
	$('#displayData').html(tableHeader);
	var logType = $('#ddlLogType').val().length != 0 ? $('#ddlLogType').val().toString():'All';
	var request = new Request();
	request.url = "../cgi/cgi_CCMLogs.py";
	request.statusType="GetLogs";
	request.parameters={"request_Type":"read_CCMLogs","startDate":$('#txtStartDate').val(),"endDate":$('#txtEndDate').val(),"maxLogLevel":$('#txtLogLevel').val(),"logType":logType}
	CallPythonService(request);	
}
function GetConsoleLogs()
{	
	let  tableHeader = ` <div id="graph-water-mark" style=" width:100%; height:100%;">
	<img class="" src ="../images/loader.gif" style="margin: 50px auto; display:block;"></div>`
	$('#consoledata').html(tableHeader);
	var logType = $('#ddlLogType').val().length != 0 ? $('#ddlLogType').val().toString():'All';
	var request = new Request();
	request.url = "../cgi/cgi_CCMLogs.py";
	request.statusType="GetConsoleLogs";
	request.parameters={"request_Type":"read_ConsoleLogs","startDate":$('#StartDate').val(),"endDate":$('#EndDate').val(),"maxLogLevel":$('#txtLogLevel').val(),"logType":logType}
	CallPythonService(request);	
}
function downloadLogs()
{	
	$('#btnDownload').html('<div class="dot-carousel-white"></div>');
	$('#btnDownload').addClass('custom-disabled');
	var logType ='All';
	var request = new Request();
	request.url = "../cgi/cgi_CCMLogs.py";
	request.statusType="downloadLogs";
	request.parameters={"request_Type":"download_CCMLogs","logType":logType}
	CallPythonService(request);	
}

function downloadConselogs()
{	
	$('#btnDownload1').html('<div class="dot-carousel-white"></div>');
	$('#btnDownload1').addClass('custom-disabled');
	var logType ='All';
	var request = new Request();
	request.url = "../cgi/cgi_CCMLogs.py";
	request.statusType="downloadConsloeLogs";
	request.parameters={"request_Type":"download_ConsoleLogs","logType":logType}
	CallPythonService(request);	
}


function CallPythonService(request) {
	request.parameters.uuid=uuid;
    $.ajax({
        type: "Get",
        url: request.url,
        contentType: 'application/json',
        dataType: 'json',
        headers: { 'Access-Control-Allow-Origin': '*' },
        data: request.parameters,
        success: function (response) {
			// $('#displayData').html('');
			if(response.status == 'fail')
				notify(response.description,response.description,response.status);
			else{
				BindResponseData(request.statusType,response);
			}
        },
        error: function (ex) {
			$('#displayData').html('');
			// $('#consoledata').html('');
            if(!isProduction){
				console.log(ex);
			}
        }
    });
}
function BindResponseData(statusType, response) {
	var headers =response.headers;
	var propetyName = response.propetyName
    if (statusType === 'GetLogs') {         
		$('#displayData').html('');  
        var tableHeader = '<table class="table table-striped table-bordered" id="tblLogsData"><thead><tr class="tbheader">'
		var headerTxt = '';
		$.each(headers, function (i, item) {
			var cls = '';
			if(item == 'Message')
				cls = 'class="messageIDtxt"'
			headerTxt +='<th '+cls+' >'+item+'</th>'
		});		
		tableHeader += headerTxt+'</tr></thead><tbody id="tbodyLogsData"></tbody></table>'
        $('#displayData').html(tableHeader);
        $.each(response.logsData, function (i, item) {
            var records = '<tr>'; //'<tr><td>' + SplitDateTime(item.Date,"date") + '</td><td>' + SplitDateTime(item.Date,"time") + '</td><td>' + 'Element' + '</td><td>' + 'Error' + '</td><td>' + 'State' + '</td><td>' + item.Log + '</td></tr>'
            
			var recordsTxt = '';
			$.each(propetyName, function (i, prop) {
				var cls = '';
				if(prop == 'message')
					cls = 'class="messageIDtxt"'
				recordsTxt +='<td '+cls+' >'+item[prop]+'</td>';
			});
			records += recordsTxt+'</tr>'
			
			$('#tbodyLogsData').append(records);
        });
			$('#tblLogsData').DataTable({
				responsive: true,
				"columns": [
					{ "type": "date", "targets": [0],width:"180px"},
					{width:"80px"},
					{width:"100px"},
					{width:"80px"},
					{width:"40px"},
					{width:"50px"},
					{width:"300px"}
				],
				columnDefs: [
					{
					targets: 6, // Column index where you want to apply the custom rendering (0 for the first column)
					render: function(data, type, row) {
						// Adjust the 'maxCharacters' variable to set the maximum number of characters you want to display
						var maxCharacter = 60;
						if (type === 'display' && data.length > maxCharacter) {
							return data.substr(0, maxCharacter) + '...'; // Truncate the content
						}
						return data;
					}
					}
				]
			});
    }
	else if (statusType === 'GetConsoleLogs') {         
		$('#consoledata').html('');  
        var tableHeader = '<table class="table table-striped table-bordered" id="tblConsoleLogsData" style="width:100% !important"><thead><tr class="tbheader">'
		var headerTxt = '';
		$.each(headers, function (i, item) {
			var cls = '';
			if(item == 'Message')
				cls = 'class="messageIDtxt"'
			headerTxt +='<th '+cls+' >'+item+'</th>'
		});		
		tableHeader += headerTxt+'</tr></thead><tbody id="consoleLogsData"></tbody></table>'
        $('#consoledata').html(tableHeader);
        $.each(response.logsData, function (i, item) {
            var records = '<tr>'; //'<tr><td>' + SplitDateTime(item.Date,"date") + '</td><td>' + SplitDateTime(item.Date,"time") + '</td><td>' + 'Element' + '</td><td>' + 'Error' + '</td><td>' + 'State' + '</td><td>' + item.Log + '</td></tr>'
            
			var recordsTxt = '';
			$.each(propetyName, function (i, prop) {
				var cls = '';
				if(prop == 'message')
					cls = 'class="messageIDtxt"'
				recordsTxt +='<td '+cls+' >'+item[prop]+'</td>';
			});
			records += recordsTxt+'</tr>'
			
			$('#consoleLogsData').append(records);
        });
			$('#tblConsoleLogsData').DataTable({
				responsive: true,
				"columns": [
					{ "type": "date", "targets": [0],width:"100px"},
					{width:"600px"},
				],
				columnDefs: [
					{
					targets: 1, // Column index where you want to apply the custom rendering (0 for the first column)
					render: function(data, type, row) {
						// Adjust the 'maxCharacters' variable to set the maximum number of characters you want to display
						var maxCharacter = 60;
						if (type === 'display' && data.length > maxCharacter) {
							return data.substr(0, maxCharacter) + '...'; // Truncate the content
						}
						return data;
					}
					}
				]
			});
    }
	else if (statusType === "downloadLogs" ) {
		if(response["filename"]){

			var link = document.createElement("a");
			link.setAttribute('download', response['filename']);
			link.href = response['download_file'];
			document.body.appendChild(link);
			link.click();
			link.remove();
		}
		else{
			showModal("Error", "No data to download!")
		}
		$('#btnDownload').html('Download');
		$('#btnDownload').removeClass('custom-disabled');
	}  
	else if (statusType === "downloadConsloeLogs" ) {
		if(response["filename"]){
			var link = document.createElement("a");
			link.setAttribute('download', response['filename']);
			link.href = response['download_file'];
			document.body.appendChild(link);
			link.click();
			link.remove();
		}
		else{
			showModal("Error", "No data to download!")
		}
		$('#btnDownload1').html('Download');
		$('#btnDownload1').removeClass('custom-disabled');
	}  
	

    
}
function SplitDateTime(dateTime,type)
{
	var data=dateTime.split("-");
	if(type == 'date')
		return data[0];
	else
		return data[1];
}

Date.prototype.addHours = function(h) {    
   this.setTime(this.getTime() - (h*60*1000)); 
   return this;   
}
function ConvertDateFormat2(YYYmmdd)
{
	var lst=YYYmmdd.split('-');
	return ((parseInt(lst[1])+1) < 10 ? '0'+(parseInt(lst[1])+1) : (parseInt(lst[1])+1))+"/"+lst[2]+"/"+lst[0];
}
function ConvertToLocalDate(UTCDate,UtcTime)
{
	var utcDate = UTCDate+'T'+UtcTime+':00'; //'2011-06-29T16:52:48.000Z';  // ISO-8601 formatted date returned from server
	var localDate = new Date(utcDate);
	localDate.addHours(localDate.getTimezoneOffset())
	return ConvertDateFormat2(localDate.getFullYear()+'-'+ (localDate.getMonth()<10? ('0'+localDate.getMonth()):localDate.getMonth())+'-'+(localDate.getDate()<10?('0'+localDate.getDate()):localDate.getDate()));
}
function ConvertToLocalTime(UTCDate,UtcTime)
{
	var utcDate = UTCDate+'T'+UtcTime+':00'; //'2011-06-29T16:52:48.000Z';  // ISO-8601 formatted date returned from server
	var localDate = new Date(utcDate);
	localDate.addHours(localDate.getTimezoneOffset())
	return (localDate.getHours()<10?('0'+localDate.getHours()):localDate.getHours())+':'+(localDate.getMinutes()<10?('0'+localDate.getMinutes()):localDate.getMinutes());
}
