let TableInformationController = {
	user: null,
	language: '',
	data: null,
	dataBBDD: null,
	sentido: '',
	years: null,
	yearsFlag: false,
	yearSelected: '',

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.data = null;
		self.dataBBDD = null;
		self.sentido = '';
		self.years = null;
		self.yearsFlag = false;
		self.yearSelected = '';
	},

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

		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('.', '_');

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

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

		self.loadLang();

		ajaxComunCallWithCallback('getDBMaintenanceInfo', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;
				self.dataBBDD = ajaxReturn.resultSchemas;

				// Tablas de resultados
				self.renderData();
				self.renderDataBBDD();
			}
		});

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	renderData() {
		let self = this;

		$('#resultTable').show();
		let excelTitle = pf.const.language.RSC1943;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC1069}">${pf.const.language.RSC1069}</th>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC1070}">${pf.const.language.RSC1070}</th>
					<th scope="col" title="${pf.const.language.RSC1313} (MB)">${pf.const.language.RSC1313} (MB)</th>
					<th scope="col" title="${pf.const.language.RSC1977}">${pf.const.language.RSC1977}</th>
					<th scope="col" title="${pf.const.language.RSC1978}">${pf.const.language.RSC1978}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td data-id="schema">schema</td>
					<td data-id="name">name</td>
					<td data-id="rows">rows</td>
					<td data-id="size">size</td>
					<td data-id="buttons">archive</td>
					<td data-id="buttons">unarchive</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.data.length;

		let buttonArchiveHtml = `
			<button class="btn table-button main-color-text archive" title="${pf.const.language.RSC1977}" data-toggle="modal" data-target="#modalYears">
				${stcmbackend.svg.bigArrowBarDownWithoutColor}
			</button>
		`;

		let buttonUnarchiveHtml = `
			<button class="btn table-button main-color-text unarchive" title="${pf.const.language.RSC1978}">
				${stcmbackend.svg.bigArrowBarUpWithoutColor}
			</button>
		`;

		for(let i = 0; i < size; i++) {
			let buttonArchive = '';
			let buttonUnarchive = '';
			let dataYear = '';

			if(self.data[i].TABLE_NAME == 'ofmsg') {
				buttonArchive = buttonArchiveHtml;
			}

			if(self.data[i].TABLE_NAME.indexOf('ofmsg_h_') !== -1) {
				dataYear = self.data[i].TABLE_NAME.replace('ofmsg_h_', '');
				buttonUnarchive = buttonUnarchiveHtml;
			}

			table += `
				<tr>
					<td class="text-truncate" title="${self.data[i].TABLE_SCHEMA}">${self.data[i].TABLE_SCHEMA}</td>
					<td class="text-truncate" title="${self.data[i].TABLE_NAME}">${self.data[i].TABLE_NAME}</td>
					<td class="text-truncate" title="${self.data[i].TABLE_ROWS}">${self.data[i].TABLE_ROWS}</td>
					<td class="text-truncate" title="${self.data[i].SIZE_MB}">${self.data[i].SIZE_MB}</td>
					<td class="text-truncate text-center" title="">${buttonArchive}</td>
					<td class="text-truncate text-center" title="" data-year="${dataYear}">${buttonUnarchive}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title == 'buttons') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '90px', targets: 2},
				{width: '90px', targets: 3},
				{width: '75px', targets: 4},
				{width: '75px', targets: 5}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

		// 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;

		// Archivar mensajes
		$('.archive').off().on('click', function() {
			self.sentido = 'O';

			if(self.yearsFlag) {
				$('#tableYears').dataTable().fnDestroy();
			} else {
				self.yearsFlag = true;
			}

			ajaxComunCallWithCallback('getYearsToArchiveOfmsg', {}, function(ajaxReturn) {
				if(ajaxReturn) {
					self.years = ajaxReturn.result;

					// Modal de años
					self.renderYears();
				}
			});
		});

		// Desarchivar mensajes
		$('.unarchive').off().on('click', function() {
			self.sentido = 'I';
			self.yearSelected = $(this).parent().data('year');
			
			self.archiveOfmsgFromFullYear();
		});
	},

	renderDataBBDD() {
		let self = this;

		let excelTitle = pf.const.language.RSC2014;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC1313} (MB)">${pf.const.language.RSC1313} (MB)</th>
				</tr>
			</thead>

			<thead class="filtersResultBBDD">
				<tr>
					<td data-id="name">name</td>
					<td data-id="size">size</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.dataBBDD.length;
		for(let i = 0; i < size; i++) {
			let name = 'DB Name';
			let size = 'DB Size in MB';
			table += `
				<tr>
					<td class="text-truncate" title="${self.dataBBDD[i][name]}">${self.dataBBDD[i][name]}</td>
					<td class="text-truncate" title="${self.dataBBDD[i][size]}">${self.dataBBDD[i][size]}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title == 'buttons') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#registersBBDD').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '90px', targets: 1}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

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

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

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

	renderYears() {
		let self = this;

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

			<thead class="filtersYears">
				<tr>
					<td>year</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.years.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr class="c-pointer" data-year="${self.years[i].yearMsg}">
					<td class="text-truncate" title="${self.years[i].yearMsg}">${self.years[i].yearMsg}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

		let tableYears = $('#tableYears').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(tableYears, 'filtersYears');

		$('#tableYears tbody').off().on('click', 'tr', function() {
			self.yearSelected = $(this).attr('data-year');

			$('#closeYears').trigger('click');

			self.archiveOfmsgFromFullYear();
		});
	},

	archiveOfmsgFromFullYear() {
		let self = this;

		let parameters = {
			year: self.yearSelected,
			sentido: self.sentido
		};
		ajaxComunCallWithCallback('archiveOfmsgFromFullYear', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC1943;

				// Archivar
				let successContent = pf.const.language.RSC2107;

				// Desarchivar
				if(self.sentido == 'I') {
					successContent = pf.const.language.RSC2108;
				}

				pf.utils.showInfoDialog(successTitle, successContent);

				loadHTML('inc/mantenimiento_sistema/table_information.html', 'wrapper', TableInformationController);
			}
		});
	}
};