let PerfilesController = {
	language: '',
	profiles: null,
	changes: null,
	select: null,
	arrayDelMult: [],

	reset() {
		let self = this;

		self.language = pf.const.language_table;
		self.profiles = '';
		self.changes = [];
		self.select = '';
		self.arrayDelMult = [];
	},

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

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

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

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

		let nav = `
			${createSubOptionNew(jsonsubopt.new)}
		`;

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

		$('#new svg').css({'width': '24px', 'height': '24px'});

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

		ajaxComunCallWithCallback('getProfiles', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.profiles = ajaxReturn.result;
				if(!Array.isArray(self.profiles)) {
					self.profiles = [];
				}

				self.printProfiles();
			}
		});

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

		// Collapse
		addEventArrowTableHeader();
	},

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

		// TITLES
		$('.deleteMultTitle').attr('title', pf.const.language.RSC95);
	},

	applyEvents() {
		$('#new').click(function() {
			window.location.href = '#!perfiles_new';
		});
	},

	printProfiles() {
		let self = this;

		let table = `
			<table id="tableProfiles" 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.RSC134}">${pf.const.language.RSC134}</th>
						<th scope="col" title="${pf.const.language.RSC595}">${pf.const.language.RSC595}</th>
						<th scope="col" title="${pf.const.language.RSC126}">${pf.const.language.RSC126}</th>
						<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
					</tr>
				</thead>

				<thead class="filtersProfiles">
					<tr>
						<td>selector</td>
						<td>perfil</td>
						<td>predefinido</td>
						<td>activo</td>
						<td>acciones</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.profiles.length;
		for(let i = 0; i < size; i++) {
			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.profiles[i].descripcion}">${(self.profiles[i].descripcion != '' ? self.profiles[i].descripcion : '-')}</td>
					<td class="pl-0 c-pointer editRow">
						<span class="d-none">${(self.profiles[i].default == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<div class="custom-control custom-switch">
							<input id="def_${self.profiles[i].isocode}" type="checkbox" class="custom-control-input uSwitch" ${(self.profiles[i].default == 1 ? 'checked' : '')} disabled>
							<label id="label_${self.profiles[i].isocode}" for="def_${self.profiles[i].isocode}" class="custom-control-label"></label>
						</div>
					</td>
					<td class="pl-0 c-pointer editRow">
						<span class="d-none" data-id="${i}">${(self.profiles[i].enabled == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<div class="custom-control custom-switch">
							<input id="idioma_${i}" type="checkbox" class="custom-control-input uSwitch" data-id="${i}" ${(self.profiles[i].enabled == 1 ? 'checked' : '')} disabled>
							<label for="idioma_${i}" class="custom-control-label c-pointer enableIdioma" data-id="${i}"></label>
						</div>
					</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
		$('#tableProfiles .filtersProfiles td').each(function() {
			let title = $(this).text();
			let value = `<input type="text" class="form-control form-control-sm">`;

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

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

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

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

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

		// Dar estilo al boton de 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(tableProfiles, 'filtersProfiles');

		// Eventos
		self.applyEventsTable(tableProfiles);

		$('#tableProfiles').on('draw.dt', function() {
			self.applyEventsTable(tableProfiles);
		});
	},

	applyEventsTable(dataTable) {
		let self = PerfilesController;

		// Eventos del input global
		globalSelectionInputActions();

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

			sessionStorage.setItem('profile', btoa(JSON.stringify(self.profiles[id])));
			window.location.href = '#!perfiles_edit';
		})

		// Eliminar perfil
		$('.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.RSC553;
			let alertText = pf.const.language.RSC554;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteProfile(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) {
				self.arrayDelMult.push(id);
			} else {
				let index = self.arrayDelMult.indexOf(id);
				self.arrayDelMult.splice(index, 1);
			}

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

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

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

		let parameters = {
			profiles: JSON.stringify(profiles)
		};
		ajaxComunCallWithCallback('deleteProfile', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let errorTitle = pf.const.language.RSC78;
				let errorContent = pf.const.language.RSC106;
				pf.utils.showInfoDialog(errorTitle, errorContent);
				loadHTML('inc/configuracion/perfiles.html', 'wrapper', PerfilesController);
			}
		});
	}
};