class TableCountries {
	constructor(type = 0, actions) {
		this.type = type;
		this.actionsTable = actions;
		this.data = null;
		this.countries = [];
		this.modality = null;
		this.admin = null;
		this.surname = true;

		this.allCountries = false;
	}

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

		self.modality = modality;
		self.allCountries = allCountries;

		if(self.data) {
			self.renderTable();
		} else {
			self.requestCountries();
		}
	}

	requestCountries() {
		let self = this;

		clearGeneralModal();

		self.data = pf.countryOptions;

		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="selectCountries" 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.RSC437}">${pf.const.language.RSC437}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC953}">${pf.const.language.RSC953}</th>
					</tr>
				</thead>

				<thead class="filtersCountry">
					<tr>
						${filterCheckbox}
						<td>ISO</td>
						<td>Country</td>
						<td>Currency</td>
					</tr>
				</thead>

				<tbody>
		`;

		// 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.allCountries == false && allowedCountries.indexOf(self.data[i].isocode) == -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.countries.length; j++) {
					if(self.countries[j].isocode == self.data[i].isocode) {
						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].isocode}" class="${(self.type === 1 ? 'c-pointer' : 'user_selected')}" data-id="${i}">
					${bodyCheckbox}
					<td class="text-truncate" title="${self.data[i].isocode}">${self.data[i].isocode}</td>
					<td class="text-truncate" title="${self.data[i].descripcion}">${self.data[i].descripcion}</td>
					<td class="text-truncate" title="${self.data[i].currency}">${self.data[i].currency}</td>
				</tr>
			`;
		}

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

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

		// Setup - add a text input to each footer cell
		$('#' + this.modality + ' .filtersCountry 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 tableCountries = $('#' + this.modality).DataTable({
			language: pf.const.language_table,
			scrollY: scroll,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			columnDefs: columnDefs,
			aaSorting: []
		});

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

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

		// Apply the search
		applyTheSearch(tableCountries, 'filtersCountry');

		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 países
			$('#selectCountries').off().on('click', function() {
				$('#closeUser').trigger('click');
				setTimeout(function() {
					tableCountries.destroy();
					self.countries = [];

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

					self.eventsTable(0);
				}, 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 = self.data[id];

		switch(self.actionsTable) {
			case 'editProjectCountry':
				ProyectosEditController.clickEvents(response);
				break;
			case 'newProjectCountry':
				ProyectosNewController.clickEvents(response);
				break;
			case 'newMissionCountry':
				MisionesNewController.clickEvents(response);
				break;
			case 'editMissionCountry':
				MisionesEditController.clickEvents(response);
				break;
			case 'muestreoDetallado':
				MuestreoDetalladoController.clickEvents(response);
				break;
			case 'newUserCountry':
				UsuariosNuevoController.clickEvents(response);
				break;
			case 'editUserCountry':
				UsuariosEditarController.clickEvents(response);
				break;
			case 'newGroupCountry':
				GruposNuevoController.clickEvents(response);
				break;
			case 'editGroupCountry':
				GruposEditarController.clickEvents(response);
				break;
			case 'newDifusionCountry':
				DifusionNewController.clickEvents(response);
				break;
			case 'editDifusionCountry':
				DifusionEditController.clickEvents(response);
				break;
			case 'newNotificacionCountry':
				NotificacionesNuevaController.clickEvents(response);
				break;
			case 'editNotificacionCountry':
				NotificacionesEditarController.clickEvents(response);
				break;
			case 'newCubosCountry':
				CubosNewController.clickEvents(response);
				break;
			case 'editCubosCountry':
				CubosEditController.clickEvents(response);
				break;
			case 'newAdministradorCountry':
				AdministradoresNuevoController.clickEvents(response);
				break;
			case 'editAdministradorCountry':
				AdministradoresEditarController.clickEvents(response);
				break;
			case 'newPerfilacionCountry':
				PerfilacionNewController.clickEvents(response);
				break;
			case 'editPerfilacionCountry':
				PerfilacionEditController.clickEvents(response);
				break;
			case 'newHTMLCountry':
				HtmlNuevoController.clickEvents(response);
				break;
			case 'editHTMLCountry':
				HtmlEditarController.clickEvents(response);
				break;
			case 'newAddonsCountry':
				AddonsNewController.clickEvents(response);
				break;
			case 'editAddonsCountry':
				AddonsEditController.clickEvents(response);
				break;
			case 'perfil':
				PerfilController.clickEvents(response);
				break;
			case 'pagosAutomatizadosNewCountry':
				PagosAutomatizadosNewController.clickEvents(response);
				break;
			case 'pagosAutomatizadosEditCountry':
				PagosAutomatizadosEditController.clickEvents(response);
				break;
			case 'asesores':
				AsesoresController.clickEvents(self.countries);
				break;
			case 'inversion':
				InversionController.clickEvents(response);
				break;
			case 'passiveTracking':
				PassiveTrackingController.clickEvents(response);
				break;
			case 'registerCountry':
				FormularioRegistroController.clickEvents(response);
				break;
			case 'newTenantCountry':
				TenantNewController.clickEvents(response);
				break;
			case 'editTenantCountry':
				TenantEditController.clickEvents(response);
				break;
			case 'catalogacionAsesores':
				CatalogacionAsesoresController.clickEvents(self.countries);
				break;
			case 'perSinFinalizar':
				PerSinFinalizarController.clickEvents(self.countries);
				break;
			case 'newCPGCountry':
				CPGNewController.clickEvents(response);
				break;
			case 'editCPGCountry':
				CPGEditController.clickEvents(response);
				break;
			case 'pagos':
				PagosController.clickEvents(response);
				break;
			case 'pagosDetalle':
				PagosDetalleController.clickEvents(response);
				break;
			case 'users':
				UsuariosController.clickCountryEvents(self.countries);
				break;
			case 'newSegmentCountry':
				SegmentacionesNewController.clickEvents(response);
				break;
			case 'editSegmentCountry':
				SegmentacionesEditController.clickEvents(response);
				break;
			case 'segmentacionesAutomatizadasNewCountry':
				SegmentacionesAutomatizadasNewController.clickEvents(response);
				break;
			case 'segmentacionesAutomatizadasEditCountry':
				SegmentacionesAutomatizadasEditController.clickEvents(response);
				break;
			case 'productsNew':
				ProductosNewController.clickEvents(response);
				break;
			case 'productsEdit':
				ProductosEditController.clickEvents(response);
				break;
			case 'templatesNew':
				TemplatesNewController.clickEvents(response);
				break;
			case 'templatesEdit':
				TemplatesEditController.clickEvents(response);
				break;
			case 'newProductProjectCountry':
				ProductoProyectoNewController.clickEvents(response);
				break;
			case 'editProductProjectCountry':
				ProductoProyectoEditController.clickEvents(response);
				break;
			case 'newProductMissionCountry':
				ProductoMisionNewController.clickEvents(response);
				break;
			case 'editProductMissionCountry':
				ProductoMisionEditController.clickEvents(response);
				break;
			case 'clientesEdit':
				ClientsEditController.clickEvents(response);
				break;
			case 'newCustomer':
				CustomersNewController.clickEvents(response);
				break;
			case 'editCustomer':
				CustomersEditController.clickEvents(response);
				break;
			case 'VoiceAssistantNewController':
				VoiceAssistantNewController.clickEvents(response);
				break;
			case 'VoiceAssistantEditController':
				VoiceAssistantEditController.clickEvents(response);
				break;
			case 'BotsNewController':
				BotsNewController.clickEvents(response);
				break;
			case 'BotsEditController':
				BotsEditController.clickEvents(response);
				break;
			case 'StepByStepProjectNewController':
				StepByStepProjectNewController.clickEvents(response);
				break;
			case 'StepByStepProjectEditController':
				StepByStepProjectEditController.clickEvents(response);
				break;
		}
	}
}