class TableNotifications {
	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;

		ajaxComunCallWithCallback('getCMBPNotifications', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result.reverse();
				self.renderTable();
			}
		});
	}

	renderTable() {
		let self = this;

		let table = `
			<table id="tableNotifications" 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.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC367}">${pf.const.language.RSC367}</th>
						<th scope="col" title="${pf.const.language.RSC114}">${pf.const.language.RSC114}</th>
						<th scope="col" title="${pf.const.language.RSC368}">${pf.const.language.RSC368}</th>
						<th scope="col" title="${pf.const.language.RSC369}">${pf.const.language.RSC369}</th>
						<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
					</tr>
				</thead>

				<thead class="filtersUser">
					<tr>
						<td>selector</td>
						<td>pais</td>
						<td>descripcion</td>
						<td>tipoNotificacion</td>
						<td>Activa</td>
						<td>ultima ejecucion</td>
						<td>Ovservaciones1</td>
						<td>acciones</td>
					</tr>
				</thead>

				<tbody>
		`;

		// Información de administrador
		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let userA = JSON.parse(JSONuser);
		let dateFormat = userA.formatoFecha;

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

			// Tipo de notificaciones
			let typeNotif;
			switch(parseInt(self.data[i].TipoNotificacion)) {
				case 0:
					typeNotif = pf.const.language.RSC370;
					break;
				case 1:
					typeNotif = pf.const.language.RSC371;
					break;
				case 2:
					typeNotif = pf.const.language.RSC372;
					break;
				default:
					typeNotif = '';
					break;
			}

			// Formato de fecha, el servicio devuelve DD/MM/AAAA HH:MM:SS o vacío
			let dateTime = '-';
			let fechaUltimaEjecucionOrder = '-';
			if(self.data[i].FechaUltimaEjecucion != '' && self.data[i].FechaUltimaEjecucion.includes(' ')) {
				// Para ordenación en columna
				let fechaUltimaEjecucionOrderArray = self.data[i].FechaUltimaEjecucion.split(' ');
				fechaUltimaEjecucionOrder = modifyDateFormat(fechaUltimaEjecucionOrderArray[0]).replace(/\//g, '-') + fechaUltimaEjecucionOrderArray[1];

				let dateTimeArray = self.data[i].FechaUltimaEjecucion.split(' ');
				let date = dateTimeArray[0].replace(/-/g, '/');
				if(dateFormat === 'AAAAMMDD') {
					dateTime = modifyDateFormat(date) + ' ' + dateTimeArray[1];
				} else {
					dateTime = date + ' ' + dateTimeArray[1];
				}
			}

			table += `
				<tr data-id="${i}">
					<td class="text-center">
						<div class="div-single-selection" data-id="${i}">
							<input type="checkbox" class="deleteSelection">
						</div>
					</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].country}">${(self.data[i].country != '' ? self.data[i].country : '-')}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].Descripcion}">${(self.data[i].Descripcion != '' ? self.data[i].Descripcion : '-')}</td>
					<td class="text-truncate c-pointer editRow" title="${typeNotif}">${(typeNotif != '' ? typeNotif : '-')}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].Activa}">
						<div class="custom-control custom-switch">
							<span class="d-none">${(self.data[i].Activa == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
							<input id="tellFriend" type="checkbox" class="custom-control-input uSwitch" ${(self.data[i].Activa == 1 ? 'checked' : '')} disabled>
							<label for="tellFriend" class="custom-control-label c-pointer"></label>
						</div>
					</td>
					<td class="text-truncate c-pointer editRow" title="${dateTime}">
						<span class="d-none">${fechaUltimaEjecucionOrder}</span>
						${dateTime}
					</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].Observaciones1}">${(self.data[i].Observaciones1 != '' ? self.data[i].Observaciones1 : '-')}</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="${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
		$('#tableNotifications .filtersUser td').each(function() {
			let title = $(this).text();
			let value = `<input type="text" class="form-control form-control-sm">`;

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

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

		let tableUsers = $('#tableNotifications').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '60px', targets: 1},
				{width: '60px', orderable: false, targets: 7}
			],
			scrollCollapse: true,
			scroller: false,
			paging: true,
			autoWidth: false,
			order: [[5, 'desc']],
			lengthChange: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'btn secondary-button ma-le-5',
				title: pf.const.language.RSC11,
				exportOptions: {
					format: {
						body(data, row, column, node) {
							let dev = '';
							if(column === 5) {
								dev = data.replace(/<span class="d-none">[A-Za-z0-9-.:]*<\/span>/g, '');
							} else {
								dev = data.replace(/<\/?[^>]+(>|$)/g, '');
							}
							return dev;
						}
					}
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

		$('#btn-actions').html(tableUsers.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(tableUsers, 'filtersUser');

		self.tableEvents(tableUsers);

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

	tableEvents(dataTable) {
		let self = this;

		// Eventos del input global
		globalSelectionInputActions();

		// Editar notificación
		$('.editRow').off().on('click', function() {
			let id = $(this).parent().data('id');

			self.edit(id);
		});

		// Eliminar notificación
		$('.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.RSC11;
			let alertText = pf.const.language.RSC447;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.delete(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) {
				NotificacionesController.arrayDelMult.push(id);
			} else {
				let index = NotificacionesController.arrayDelMult.indexOf(id);
				NotificacionesController.arrayDelMult.splice(index, 1);
			}

			// Eventos de los inputs individuales
			deleteSelectionInputActions(NotificacionesController.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.RSC11;
			let alertText = pf.const.language.RSC1690;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.delete();
			}, function() {});
		});
	}

	edit(id) {
		let self = this;

		sessionStorage['STCMBackEnd:editNotification'] = JSON.stringify(self.data[id]);
		window.location.href = '#!notificaciones/editar';
	}

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

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

		let parameters = {
			notifications: JSON.stringify(notifications)
		};
		ajaxComunCallWithCallback('deleteCMBPNotifications', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC11;
				// Notificación eliminada correctamente
				let successContent = pf.const.language.RSC448;
				pf.utils.showInfoDialog(successTitle, successContent);
				self.data = null;
				self.setEvents();
			}
		});
	}
};