let LogsController = {
	user: null,
	language: '',
	rows: '',
	data: '',
	loaders: {},
	dateFormat: '',

	reset() {
		let self = this;

		self.user = null;
		self.today = '';
		self.language = pf.const.language_table;
		self.rows = '';
		self.data = '';
		self.loaders = {
			getCMBPLOG: false,
			getAPILOG: false
		};
		self.dateFormat = '';
	},

	setEvents() {
		let self = this;
		self.reset();

		// Información de administrador
		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		let userMail = user.email;
		let user_split = userMail.split('@');
		self.user = user_split[0].replace('.', '_');
		self.dateFormat = user.formatoFecha;

		// Reducción de Header
		headerSectionHeight(0);

		// Añadir titulo
		$('#page-title').text(pf.const.language.RSC19);

		// Opciones de header
		let jsonsubopt = {
			delete: 'delete'
		};

		let nav = `
			${createSubOptionDelete(jsonsubopt.delete)}
		`;

		// Acciones de página (flex-row-reverse)s
		$('#page-actions').html(nav);

		$('#delete svg').css('width', '16px');
		$('#delete svg').css('height', '16px');

		// Botón principal
		$('#delete').addClass('main-button');

		self.loadLang();
		self.applyEvents();

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.rows = config.LOGRowsLoad;
		self.fontName = config.FontAnalytics;

		addLoader();
		self.requestLogs();
		self.requestAPILogs();

		// Collapse
		addEventArrowTableHeader();
	},

	loadLang() {
		pf.rsc.translateByTag('text');

		// TITLES
		$('.exportTitle').attr('title', pf.const.language.RSC47);
	},

	applyEvents() {
		let self = this;

		// Borrar logs
		$('#delete').on('click', function() {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC95
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC19;
			let alertText = pf.const.language.RSC1734;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.removeLogs();
			}, function() {});
		});
	},

	requestLogs() {
		let self = this;

		let rowsFilter = '';
		if(self.rows > 0) {
			rowsFilter = self.rows;
		}

		let parameters = {
			rowsFilter: rowsFilter
		};
		ajaxComunCallWithCallback('getCMBPLOG', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;
				// Tabla de resultados
				self.renderData();

				// Control de spinner
				self.loaders.getCMBPLOG = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	renderData() {
		let self = this;

		let excelTitle = pf.const.language.RSC19;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC457}">${pf.const.language.RSC457}</th>
					<th scope="col" title="${pf.const.language.RSC438}">${pf.const.language.RSC438}</th>
					<th scope="col" title="${pf.const.language.RSC458}">${pf.const.language.RSC458}</th>
					<th scope="col" title="${pf.const.language.RSC459}">${pf.const.language.RSC459}</th>
					<th scope="col" title="${pf.const.language.RSC408}">${pf.const.language.RSC408}</th>
					<th scope="col" title="${pf.const.language.RSC777}">${pf.const.language.RSC777}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>id</td>
					<td>date</td>
					<td>type</td>
					<td>service</td>
					<td>event</td>
					<td>sistema</td>
					<td>informacion</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			let button = `
				<button type="button" class="btn table-button main-color-text searchInfo" data-toggle="modal" data-target="#infoLogModal">
					${stcmbackend.svg.bigEyeWithoutColor}
				</button>
			`;

			if(self.data[i].TypeEvent === 'Exported Payments') {
				button = `
					<a href="${stcm.const.downloads + self.data[i].SQLQuery}" class="btn table-button main-color-text">
						${stcmbackend.svg.bigDownloadWithoutColor}
					</a>
				`;
			} else if(self.data[i].TypeEvent === 'Imported Payments') {
				button = `
					<button type="button" class="btn table-button main-color-text importedPayments" data-toggle="modal" data-target="#infoLogModal">
						${stcmbackend.svg.bigDownloadWithoutColor}
					</button>
				`;
			}

			// Formato de fecha, el servicio devuelve AAAA-MM-DD HH:MM:SS
			let FechaDeAlta = '';
			let dateTimeArray = self.data[i].FechaDeAlta.split(' ');
			let date = dateTimeArray[0].replace(/-/g, '/');
			if(self.dateFormat === 'DDMMAAAA') {
				FechaDeAlta = modifyDateFormat(date) + ' ' + dateTimeArray[1];
			} else {
				FechaDeAlta = date + ' ' + dateTimeArray[1];
			}

			// Para ordenación en columna
			let fechaDeAltaOrder = self.data[i].FechaDeAlta.replace(' ', '');

			table += `
				<tr id="id-${self.data[i].id}">
					<td class="text-truncate" title="${self.data[i].id}">${self.data[i].id}</td>
					<td class="text-truncate" title="${FechaDeAlta}">
						<span class="d-none">${fechaDeAltaOrder}</span>
						${FechaDeAlta}
					</td>
					<td class="text-truncate" title="${self.data[i].TypeEvent}">${self.data[i].TypeEvent}</td>
					<td class="text-truncate" title="${self.data[i].CallerEvent}">${self.data[i].CallerEvent}</td>
					<td class="text-truncate" title="${self.data[i].LogEvent}">${self.data[i].LogEvent}</td>
					<td class="text-center">
						<span class="d-none">${(self.data[i].systemEvent == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.data[i].systemEvent == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate text-center" data-info="${i}">
						${button}
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

		$('#registers').html(table);

		// Setup - add a text input to each footer cell
		$('#registers .filtersResult td').each(function() {
			let title = $(this).text();
			let value = `<input type="text" class="form-control form-control-sm">`;

			if(title == 'sistema') {
				value = optionsSelectAllYesNo();
			}

			$(this).html(value);
		});

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '40px', targets: 0},
				{width: '110px', targets: 1},
				{width: '110px', targets: 2},
				{width: '170px', targets: 3},
				{width: '55px', targets: 5},
				{width: '80px', targets: 6}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: excelTitle,
				exportOptions: {
					format: {
						body(data, row, column, node) {
							let dev = '';
							if(column === 1) {
								dev = data.replace(/<span class="d-none">[A-Za-z0-9-.:]*<\/span>/g, '');
							} else {
								dev = data.replace(/<\/?[^>]+(>|$)/g, '');
							}
							return dev;
						}
					}
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			order: [0, 'desc']
		});

		// Ocultar botones de tabla
		hideTableButtons('registers');

		// Apply the search
		applyTheSearch(dataTable, 'filtersResult');

		// Exportar tabla
		$('#export').off().on('click', function() {
			$('#resultTable .buttons-excel').trigger('click');
		});

		self.tableEvents();

		$('#resultTable').on('draw.dt', function() {
			self.tableEvents();
		});
	},

	tableEvents() {
		let self = this;

		// Petición de información del usuario
		$('.searchInfo').off().on('click', function() {
			let id = $(this).parent().attr('data-info');

			let info = `
				<p><strong>${pf.const.language.RSC366}:</strong> ${self.data[id].id}</p>
				<p><strong>${pf.const.language.RSC457}:</strong> ${self.data[id].FechaDeAlta}</p>
				<p><strong>${pf.const.language.RSC438}:</strong> ${self.data[id].TypeEvent}</p>
				<p><strong>${pf.const.language.RSC458}:</strong> ${self.data[id].CallerEvent}</p>
				<p><strong>${pf.const.language.RSC459}:</strong> ${self.data[id].LogEvent}</p>
				<p><strong>SQLQuery:</strong> ${self.data[id].SQLQuery}</p>
				<p><strong>idTenant:</strong> ${self.data[id].idTenant}</p>
			`;

			$('#infoBody').html(info);
		});

		// Petición de archivos importados / pagados
		$('.importedPayments').off().on('click', function() {
			let id = $(this).parent().attr('data-info');

			let linksArray = self.data[id].SQLQuery.split(',');

			let info = `
				<p>
					<a href="${stcm.const.downloads + linksArray[1]}" class="btn table-button main-color-text mr-2">
						${stcmbackend.svg.bigDownloadWithoutColor}
					</a>
					${pf.const.language.RSC1779}
				</p>

				<p>
					<a href="${stcm.const.downloads + linksArray[0]}" class="btn table-button main-color-text mr-2">
						${stcmbackend.svg.bigDownloadWithoutColor}
					</a>
					${pf.const.language.RSC1780}
				</p>
			`;

			$('#infoBody').html(info);
		});
	},

	removeLogs(id) {
		ajaxComunCallWithCallback('deleteCMBPLOG', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC19;
				let successContent = pf.const.language.RSC461;
				pf.utils.showInfoDialog(successTitle, successContent);
				loadHTML('inc/configuracion/logs.html', 'wrapper', LogsController);
			}
		});
	},

	requestAPILogs() {
		let self = this;

		ajaxComunCallWithCallback('getAPILOG', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let log = ajaxReturn.result.log;
				if(ajaxReturn.result != '00') {
					if(ajaxReturn.result.error == '' || ajaxReturn.result.error == false) {
						$('#errorTitle').append(': OK');
					} else {
						$('#errorTitle').append(': ' + ajaxReturn.result.error);
					}
				} else {
					$('#errorTitle').append(': OK');
					log = [];
				}

				// Tabla de resultados de logs de API
				self.renderAPIData(log);

				// Control de spinner
				self.loaders.getAPILOG = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	renderAPIData(log) {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC19}">${pf.const.language.RSC19}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>logs</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = 0;
		let stop = 0;
		if(log.length > 0) {
			size = log.length - 1;
			if(log.length > 50) {
				stop = size - 50;
			}
		}

		for(let i = size; i > stop; i--) {
			if(!log[i]) {
				continue;
			}
			table += `
				<tr>
					<td class="text-truncate" title="${log[i]}">${log[i]}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

		$('#registers2').html(table);

		// Setup - add a text input to each footer cell
		$('#registers2 .filtersResult td').each(function() {
			let value = `<input type="text" class="form-control form-control-sm">`;

			$(this).html(value);
		});

		let dataTable = $('#registers2').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			aaSorting: [],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC981,
				className: 'd-none',
				title: pf.const.language.RSC981,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

		// Ocultar botones de tabla
		hideTableButtons('registers2');

		// Exportar tabla
		$('#exportAS').off().on('click', function() {
			$('#resultTable2 .buttons-excel').trigger('click');
		});

		// Apply the search
		applyTheSearch(dataTable, 'filtersResult');
	}
};