class TableGroups {
	constructor(type = 0, actions) {
		this.type = type;
		this.actionsTable = actions;
		this.data = null;
		this.groups = [];
		this.modality = null;
	}

	setEvents(modality = 'tableModal') {
		let self = this;

		self.modality = modality;
		if(self.data) {
			self.renderTable();
		} else {
			self.requestUsers();
		}
	}

	requestUsers() {
		let self = this;

		clearGeneralModal();

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

	renderTable() {
		let self = this;

		let headerCheckbox = '';
		let filterCheckbox = '';

		// Si la tabla de modal es de selección múltiple
		if(self.type === 1) {
			headerCheckbox = `
				<th class="text-center" scope="col" title="">
					<div class="div-global-selection">
						<input type="checkbox" class="globalSelection">
					</div>
				</th>
			`;

			filterCheckbox = `<td>selector</td>`;

			let acceptButton = `
				<button id="selectMembers" type="button" class="btn main-button" title="${pf.const.language.RSC141}">
					<span>${pf.const.language.RSC141}</span>
				</button>
			`;

			$('#divModalFooter').html(acceptButton);
		}

		let role = '';
		let roleLabel = '';
		if(this.modality == 'tableModal') {
			role = pf.const.language.RSC277;
			roleLabel = 'Role';
		} else {
			roleLabel = 'Edit';
		}

		let table = `
			<table id="${this.modality}" class="table table-hover tr-pointer">
				<thead>
					<tr>
						${headerCheckbox}
						<th scope="col">${pf.const.language.RSC123}</th>
						<th scope="col">${pf.const.language.RSC163}</th>
					</tr>
				</thead>

				<thead class="filtersUser">
					<tr>
						${filterCheckbox}
						<td>Name</td>
						<td>Admin</td>
					</tr>
				</thead>

				<tbody>
		`;

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

			let bodyCheckbox = '';

			// Si la tabla de modal es de selección múltiple
			if(self.type === 1) {
				let checked = '';
				for(let j = 0; j < self.groups.length; j++) {
					if(self.groups[j].id == self.data[i].idGroup) {
						checked = 'checked';
					}
				}

				bodyCheckbox = `
					<td class="text-center">
						<div class="div-single-selection">
							<input type="checkbox" class="selection" ${checked}>
						</div>
					</td>
				`;
			}

			table += `
				<tr id="${self.data[i].id}" class="user_selected" data-id="${i}">
					${bodyCheckbox}
					<td class="text-truncate nameUser" title="${self.data[i].name}">${self.data[i].name}</td>
					<td class="text-truncate" title="${self.data[i].userNombre} ${self.data[i].userApellidos} ${self.data[i].userApellidos2}">${self.data[i].userNombre} ${self.data[i].userApellidos} ${self.data[i].userApellidos2}</td>
				</tr>
			`;
		}

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

		if(this.modality == 'tableModal') {
			$('#headerModalTitle').text(pf.const.language.RSC6);
			$('#divTableModal').html(table);
		} else {
			$('#div' + this.modality).html(table);
		}

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

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

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

		let scroll = 300;
		if(self.modality != 'tableModal') {
			scroll = 600;
		}

		let columnDefs = [];
		if(self.type === 1) {
			columnDefs = [{width: '25px', orderable: false, targets: 0}];
		}

		let tableUsers = $('#' + this.modality).DataTable({
			language: pf.const.language_table,
			scrollY: scroll,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			columnDefs: columnDefs,
			aaSorting: [],
		});

		setTimeout(function() {
			tableUsers.columns.adjust();
		}, 200);

		// Ocultar botones de tabla
		hideTableButtons(this.modality);

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

		if(self.type === 0) {
			// Detectar click
			$('#' + this.modality + ' tbody').off().on('click', 'tr', function() {
				self.eventsTable($(this).data('id'));
				$('#closeUser').trigger('click');
			});
		} else {
			self.multiSelectTableEvents();

			$('#tableModal').on('draw.dt', function() {
				self.multiSelectTableEvents();
			});

			// Selección de múltiples miembros
			$('#selectMembers').off().on('click', function() {
				addLoader();
				$('#closeUser').trigger('click');
				setTimeout(function() {
					tableUsers.destroy();
					self.groups = [];

					let positionMember = '';
					$('#tableModal tr').each(function() {
						let cheked = $(this).find('.selection');
						if(cheked.prop('checked')) {
							positionMember = $(this).data('id');
							self.groups.push(self.data[positionMember]);
						}
					});

					self.eventsTable(0);
					removeLoader();
				}, 500);
			});
		}
	}

	multiSelectTableEvents() {
		inputControl();

		// Selección por tr
		$('#tableModal tbody tr').off().on('click', function() {
			let checkedComp = $(this).find('.selection').prop('checked');
			if(checkedComp) {
				$(this).find('.selection').prop('checked', false);
			} else {
				$(this).find('.selection').prop('checked', true);
			}

			inputControl();
		});

		// Selección por input check
		$('.selection').off().on('click', function() {
			let checkedComp = $(this).prop('checked');
			if(checkedComp) {
				$(this).prop('checked', false);
			} else {
				$(this).prop('checked', true);
			}

			inputControl();
		});

		// Marcar desmarcar todo
		$('.globalSelection').off().on('change', function() {
			if($('.globalSelection').prop('checked')) {
				$('.selection').prop('checked', true);
			} else {
				$('.selection').prop('checked', false);
			}
		});

		function inputControl() {
			// Estado del input global con respecto a los inputs en página
			if($('.selection').length == $('.selection:checked').length && $('.selection').length > 0) {
				$('.globalSelection').prop('checked', true);
			} else {
				$('.globalSelection').prop('checked', false);
			}
		}
	}

	eventsTable(id) {
		let self = this;

		let response = '';
		if(self.type === 0) {
			response = self.data[id];
		} else {
			response = self.groups;
		}

		switch(self.actionsTable) {
			case 'editUser':
				UsuariosEditarController.clickEvents(response);
				break;
			case 'newUser':
				UsuariosNuevoController.clickEvents(response);
				break;
			case 'newNotification':
				NotificacionesNuevaController.clickGroup(response);
				break;
			case 'editNotification':
				NotificacionesEditarController.clickGroup(response);
				break;
			case 'pagosAutomatizadosNew':
				PagosAutomatizadosNewController.clickGroup(response);
				break;
			case 'pagosAutomatizadosEdit':
				PagosAutomatizadosEditController.clickGroup(response);
				break;
		}
	}
}