class TableHtml {
	constructor() {
		this.data = null;
		this.excel = true;
	}

	setEvents() {
		let self = this;

		if(self.data) {
			self.renderTable();
		} else {
			self.requestData();
		}
	}

	getData() {
		return this.data;
	}

	requestData() {
		let self = this;

		stcmbackend.html.getAllCustomMenuOptionAjax(function(ajaxReturn) {
			removeLoader();
			self.data = ajaxReturn.result;
			self.renderTable();
		});
	}

	renderTable() {
		let self = this;

		let table = `
			<table id="tableHtml" class="table table-hover tRegs">
				<thead>
					<tr>
						<th class="text-center" scope="col" title="">
							<div class="div-global-selection">
								<input type="checkbox" class="globalSelection">
							</div>
						</th>
						<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC353}">${pf.const.language.RSC353}</th>
						<th scope="col" title="${pf.const.language.RSC354}">${pf.const.language.RSC354}</th>
						<th scope="col" title="${pf.const.language.RSC355}">${pf.const.language.RSC355}</th>
						<th scope="col" title="${pf.const.language.RSC17}">${pf.const.language.RSC17}</th>
						<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
					</tr>
				</thead>

				<thead class="filtersUser">
					<tr>
						<td>selector</td>
						<td>id</td>
						<td>pais</td>
						<td>optionText</td>
						<td>parent</td>
						<td>url</td>
						<td>roles</td>
						<td>acciones</td>
					</tr>
				</thead>

				<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(self.data[i].country != '' && allowedCountries.indexOf(self.data[i].country) == -1) {
				continue;
			}

			table += `
				<tr data-id="${self.data[i].id}" data-index="${i}">
					<td class="text-center">
						<div class="div-single-selection" data-id="${self.data[i].id}">
							<input type="checkbox" class="deleteSelection">
						</div>
					</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].id}">${(self.data[i].id != '' ? self.data[i].id : `<center>-</center>`)}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].country}">${(self.data[i].country != '' ? self.data[i].country : `<center>-</center>`)}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].optionText}">${(self.data[i].optionText != '' ? self.data[i].optionText : `<center>-</center>`)}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].parent}">${(self.data[i].parent != '' ? self.data[i].parent : `<center>-</center>`)}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].url}">${(self.data[i].url != '' ? self.data[i].url : `<center>-</center>`)}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].roles}">${(self.data[i].roles != '' ? self.data[i].roles : '-')}</td>
					<td class="text-center">
						<div id="dropdownActions${i}" class="div-dd-actions c-pointer" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
							${stcmbackend.svg.threeDotsVertical18}
						</div>

						<div class="dropdown-menu dropdown-menu-right shadow menu-actions" aria-labelledby="dropdownActions${i}" data-id="${self.data[i].id}" data-index="${i}">
							<p class="dropdown-item editRow">
								${stcmbackend.svg.pencilWithoutColor}
								<span>${pf.const.language.RSC225}</span>
							</p>
							<p class="dropdown-item deleteRow">
								${stcmbackend.svg.trashWithoutColor}
								<span>${pf.const.language.RSC95}</span>
							</p>
						</div>
					</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

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

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

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

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

		let dataTable = $('#tableHtml').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			scrollCollapse: true,
			scroller: false,
			paging: true,
			autoWidth: false,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '60px', targets: 1},
				{width: '60px', targets: 2},
				{width: '60px', orderable: false, targets: 7}
			],
			aaSorting: [],
			lengthChange: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'btn secondary-button ma-le-5',
				title: pf.const.language.RSC22,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
		});

		$('.dataTables_filter').hide();

		$('#btn-actions').html(dataTable.buttons().container());

		// Dar estilo al boton de excel
		if(self.excel) {
			$('.buttons-excel').removeClass('btn-secondary');
			$('.buttons-excel').attr('title', pf.const.language.RSC47);

			$('.buttons-excel').html(
				stcmbackend.svg.download +
				`<span>${pf.const.language.RSC47}</span>`
			);
		}

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

		self.tableEvents(dataTable);

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

	tableEvents(dataTable) {
		let self = this;

		// Eventos del input global
		globalSelectionInputActions();

		// Editar html
		$('.editRow').off().on('click', function() {
			let index = $(this).parent().data('index');

			sessionStorage['STCMBackEnd:editHtml'] = btoa(JSON.stringify(self.data[index]));
			window.location.href = '#!html/editar';
		})

		// Eliminar HTML
		$('.deleteRow').off().on('click', function() {
			let id = $(this).parent().data('id');

			let objInfo = {
				accept: {
					text: pf.const.language.RSC95
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC44;
			let alertText = pf.const.language.RSC356;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteHtml(id);
			}, function() {});
		});

		// Array de eliminado múltiple
		$('.deleteSelection').off().on('change', function() {
			let value = $(this).prop('checked');
			let id = $(this).parent().data('id');

			if(value) {
				HtmlController.arrayDelMult.push(id);
			} else {
				let index = HtmlController.arrayDelMult.indexOf(id);
				HtmlController.arrayDelMult.splice(index, 1);
			}

			// Eventos de los inputs individuales
			deleteSelectionInputActions(HtmlController.arrayDelMult);
		});

		// Función de borrado múltiple
		$('#multSelecDelete').off().on('click', function() {
			// Aviso de borrado múltiple
			let objInfo = {
				accept: {
					text: pf.const.language.RSC95
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC44;
			let alertText = pf.const.language.RSC1699;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteHtml();
			}, function() {});
		});
	}

	deleteHtml(id = false) {
		let self = this;

		let extensions = [];
		if(id !== false) {
			let obj = {
				id: id
			}
			extensions.push(obj);
		} else {
			let delSize = HtmlController.arrayDelMult.length;
			for(let i = 0; i < delSize; i++) {
				let obj = {
					id: HtmlController.arrayDelMult[i]
				}
				extensions.push(obj);
			}
			HtmlController.arrayDelMult = [];
		}

		let parameters = {
			extensions: JSON.stringify(extensions)
		};
		ajaxComunCallWithCallback('deleteCustomMenuById', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let title = pf.const.language.RSC95;
				let content = pf.const.language.RSC357;
				let customText = pf.const.language.RSC132;

				pf.utils.showInfoDialog(title, content, customText, function() {
					self.requestData();
				});
			}
		});
	}
}