let GruposController = {
	groups: null,
	arrayDelMult: [],

	reset() {
		let self = this;

		self.groups = null;
		self.arrayDelMult = [];
	},

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

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

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

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

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

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

		$('#newGroup svg').css('width', '24px');
		$('#newGroup svg').css('height', '24px');

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

		self.loadLanguage();

		ajaxComunCallWithCallback('getAllGroups', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.groups = ajaxReturn.result;

				self.renderGroups();
			}
		});

		$('#newGroup').click(function() {
			window.location.href = '#!grupos/nuevo';
		});

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	renderGroups() {
		let self = this;

		let render = `
			<table id="registers" 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.RSC292}">${pf.const.language.RSC292}</th>
						<th scope="col" title="${pf.const.language.RSC163}">${pf.const.language.RSC163}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
					</tr>
				</thead>

				<thead class="filtersResult">
					<tr>
						<td>selector</td>
						<td>Id</td>
						<td>Nombre</td>
						<td>Admin</td>
						<td>Pais</td>
						<td>acciones</td>
					</tr>
				</thead>

				<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		$.each(self.groups, function(i, value) {
			// Control de países permitidos
			if(self.groups[i].country == '' || allowedCountries.indexOf(self.groups[i].country) != -1) {
				render += `
					<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-ellipsis c-pointer editRowG" title="${self.groups[i].idGroup}">${self.groups[i].idGroup}</td>
						<td class="text-ellipsis c-pointer editRowG" title="${self.groups[i].name}">${self.groups[i].name}</td>
						<td class="text-ellipsis c-pointer editRowG" title="${self.groups[i].userNombre} ${self.groups[i].userApellidos} ${self.groups[i].userApellidos2}">${self.groups[i].userNombre} ${self.groups[i].userApellidos} ${self.groups[i].userApellidos2}</td>
						<td class="text-ellipsis c-pointer editRowG" title="${self.groups[i].country}">${self.groups[i].country}</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 editRowG">
									${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>
				`;
			}
		});

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

		// Print usersAPI
		$('#resultTable').html(render);

		// 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 == 'selector' || title === 'acciones') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let excelTitle = pf.const.language.RSC6;

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

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

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

		$('#btn-actions').html(dataTable.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>`
		);

		self.dataEvents(dataTable);

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

	dataEvents(dataTable) {
		let self = this;

		// Eventos del input global
		globalSelectionInputActions();

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

			sessionStorage['STCMBackEnd:editGroup'] = btoa(JSON.stringify(self.groups[id]));
			window.location.href = '#!grupos/editar';
		});

		// Eliminar grupo
		$('.deleteRow').off().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.RSC6;
			let alertText = pf.const.language.RSC975;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteGroup(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.RSC6;
			let alertText = pf.const.language.RSC1686;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteGroup();
			}, function() {});
		});
	},

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

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

		let parameters = {
			groups: JSON.stringify(groups)
		};
		ajaxComunCallWithCallback('deleteGroup', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let infoTitle = pf.const.language.RSC6;
				let infoContent = pf.const.language.RSC974;
				pf.utils.showInfoDialog(infoTitle, infoContent);
				loadHTML('inc/grupos/grupos.html', 'wrapper', GruposController);
			}
		});
	}
};