class TableSegmentations {
	constructor(type = 0, actions, country, arraySegmentacionesACargar) {
		this.type = type;
		this.actionsTable = actions;
		this.data = null;
		this.modality = null;
		this.segmentaciones = [];
		this.country = country;
		this.loadedSegmentations = arraySegmentacionesACargar;
	}

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

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

	requestData() {
		let self = this;

		clearGeneralModal();

		ajaxComunCallWithCallback('getAllSegmentaciones', {}, 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="selectSegmentations" type="button" class="btn main-button" title="${pf.const.language.RSC141}">
					<span>${pf.const.language.RSC141}</span>
				</button>
			`;

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

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

				<thead class="filtersUser">
					<tr>
						${filterCheckbox}
						<td>Descripcion</td>
						<td>surveyls_title</td>
						<td>surveyls_description</td>
						<td>country</td>
					</tr>
				</thead>

				<tbody>
		`;

		// En caso de que en el constructor se especifique un país,
		// se cargan solo las segmentaciones de ese país.
		// En el caso contrario se cargan todas.

		if(self.country !== null) {
			let size = self.data.length;
			let dataCountry = [];
			for(let index = 0; index < size; index++) {
				if(self.data[index].country == self.country) {
					dataCountry.push(self.data[index]);
				}
			}
			self.data = dataCountry;
		}

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			let bodyCheckbox = '';

			// Si la tabla de modal es de selección múltiple
			if(self.type === 1) {
				let checked = '';
				if(self.loadedSegmentations.includes(self.data[i].Descripcion)) {
					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].idSegmentacion}" class="user_selected edit-group" data-id="${i}">
					${bodyCheckbox}
					<td class="text-truncate" title="${self.data[i].Descripcion}">${self.data[i].Descripcion}</td>
					<td class="text-truncate" title="${self.data[i].surveyls_title}">${self.data[i].surveyls_title}</td>
					<td class="text-truncate" title="${self.data[i].surveyls_description}">${self.data[i].surveyls_description}</td>
					<td class="text-truncate" title="${self.data[i].country}">${self.data[i].country}</td>
				</tr>
			`;
		}

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

		if(this.modality == 'tableModal') {
			$('#headerModalTitle').text(pf.const.language.RSC1741);
			$('#divTableModal').html(table);
		} else {
			$('#resultTable').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 == 'active' || title == 'perfilacion') {
				value = optionsSelectAllYesNo();
			} else if(title == 'selector') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let tableSegmentations = '';

		let columnDefs = [
			{width: '200px', targets: 0},
			{width: '200px', targets: 1},
			{width: '60px', targets: 3}
		];

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

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

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

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

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

		if(self.modality != 'tableModal') {
			// Activación de botón de exportar del navegador
			$('#resultTable .buttons-excel').hide();
			$('#exportUsers').off().on('click', function() {
				$('#resultTable .buttons-excel').trigger('click');
			});
		}

		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 segmentaciones
			$('#selectSegmentations').off().on('click', function() {
				addLoader();
				$('#closeUser').trigger('click');
				setTimeout(function() {
					tableSegmentations.destroy();
					self.segmentaciones = [];

					let positionMember = '';
					$('#tableModal tr').each(function() {
						let cheked = $(this).find('.selection');
						if(cheked.prop('checked')) {
							positionMember = $(this).data('id');
							self.segmentaciones.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.segmentaciones;
		}

		switch(self.actionsTable) {
			case 'muestreoDetalladoMAZSeg':
				MuestreoDetalladoMAZSegController.clickSegmentation(response);
				break;
		}
	}
}