let IdiomasController = {
	language: '',
	idiomas: null,
	changes: null,
	select: null,
	defaultLanguage: '',
	newDefaultLanguage: '',
	defaultISO: '',

	reset() {
		let self = this;

		self.language = pf.const.language_table;
		self.idiomas = '';
		self.changes = [];
		self.select = '';
		self.defaultLanguage = '';
		self.newDefaultLanguage = '';
		self.defaultISO = '';
	},

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

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

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

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

		let nav = `
			${createSubOptionSave(jsonsubopt.save)}
		`;

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

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

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

		// Collapse
		addEventArrowTableHeader();
	},

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

	applyEvents() {
		let self = this;

		$('#save').click(function() {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC78
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC78;
			let alertText = pf.const.language.RSC105;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.updateIdiomas();
			}, function() {});
		});
	},

	getIdiomas() {
		let self = this;

		ajaxComunCallWithCallback('getIdiomas', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.idiomas = ajaxReturn.result;

				// Búsqueda de idioma por defecto
				let size = self.idiomas.length;
				for(let i = 0; i < size; i++) {
					if(self.idiomas[i].default == 1) {
						self.defaultLanguage = self.idiomas[i];
						self.defaultISO = self.idiomas[i].isocode;
						break;
					}
				}

				self.printIdiomas();
			}
		});
	},

	printIdiomas() {
		let self = this;

		let table = `
			<table id="tableIdiomas" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="ISO">ISO</th>
						<th scope="col" title="${pf.const.language.RSC552}">${pf.const.language.RSC552}</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>
					</tr>
				</thead>

				<thead class="filtersIdiomas">
					<tr>
						<td>iso</td>
						<td>pais</td>
						<td>predefinido</td>
						<td>activo</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.idiomas.length;
		for(let i = 0; i < size; i++) {
			let defaultDis = '';
			if(self.idiomas[i].enabled == 1) {
				defaultDis = '';
			}

			table += `
				<tr data-id="${i}">
					<td class="text-truncate desc" title="${self.idiomas[i].isocode}">${(self.idiomas[i].isocode != '' ? self.idiomas[i].isocode : '-')}</td>
					<td class="text-truncate desc" title="${self.idiomas[i].descripcion}">${(self.idiomas[i].descripcion != '' ? self.idiomas[i].descripcion : '-')}</td>
					<td class="pl-0">
						<span class="d-none">${(self.idiomas[i].default == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<div class="custom-control custom-switch">
							<input id="def_${self.idiomas[i].isocode}" type="checkbox" class="custom-control-input uSwitch defaultLanguageInput" ${(self.idiomas[i].default == 1 ? 'checked' : '')} ${defaultDis}>
							<label id="label_${self.idiomas[i].isocode}" for="def_${self.idiomas[i].isocode}" class="custom-control-label c-pointer defaultLanguage"></label>
						</div>
					</td>
					<td class="pl-0">
						<span class="d-none" data-id="${i}">${(self.idiomas[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 enableIdiomaInput" data-id="${i}" ${(self.idiomas[i].enabled == 1 ? 'checked' : '')}>
							<label for="idioma_${i}" class="custom-control-label c-pointer enableIdioma" data-id="${i}"></label>
						</div>
					</td>
				</tr>
			`;
		}

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

		$('#resultTable').html(table);

		// Setup - add a text input to each footer cell
		$('#tableIdiomas .filtersIdiomas 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();
			}

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

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

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

		$('#btn-actions').html(tableIdiomas.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*
		tableIdiomas.columns().eq(0).each(function(colIdx) {
			$('input', $('.filtersIdiomas td')[colIdx]).on('keyup change', function() {
				tableIdiomas
					.column(colIdx)
					.search(this.value)
					.draw();
				$(this).blur().focus();
			});
			$('select', $('.filtersIdiomas td')[colIdx]).on('change', function() {
				tableIdiomas
					.column(colIdx)
					.search(this.value)
					.draw();
				$(this).blur().focus();
			});

			tableIdiomas
				.column(1)
				.search(self.select)
				.draw();
			$(this).blur().focus();
		});

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

	applyEventsTable() {
		let self = IdiomasController;

		// Limpieza de inputs con nuevo renderizado de tabla
		$('.defaultLanguageInput').prop('checked', false);
		$('#def_' + self.defaultISO).prop('checked', true);

		// Idioma por defecto
		$('.defaultLanguageInput').off().on('click', function() {
			let checked = ($(this).prop('checked'));
			$('.defaultLanguageInput').prop('checked', false);
			//we have selected a new language
			if(checked) {
				self.defaultISO = $(this).attr('id').replace('def_', '');
				$(this).prop('checked', true);
				let thisParent = $(this).parent().parent().parent();
				if(!thisParent.find('.enableIdiomaInput').prop('checked'))
					thisParent.find('.enableIdioma').trigger('click');
				let descripcion = $(this).parent().parent().parent().find('.desc').text();
				self.newDefaultLanguage = {
					default: '1',
					descripcion: descripcion,
					enabled: '1',
					isocode: self.defaultISO
				};
			} else {
				$(this).prop('checked', false);
				self.newDefaultLanguage ='';
			}
		});

		$('.enableIdioma').off().on('click', function() {
			let id = $(this).data('id');
			let idioma = self.idiomas[id];
			let checked = !$(this).parent().find('.enableIdiomaInput').prop('checked');
			// Activación de input de predefinido
			let thisParent = $(this).parent().parent().parent();

			if(!checked && thisParent.find('.defaultLanguageInput').prop('checked')) {
				thisParent.find('.defaultLanguageInput').prop('checked', false);
				if(idioma.isocode == self.newDefaultLanguage.isocode) {
					self.newDefaultLanguage = '';
				}
			}

			// Buscar si esta en la lista de cambios
			if(self.changes.length == 0) {
				if(idioma.enabled == 1) {
					idioma.enabled = 0;
					self.idiomas[id].enabled = 0;
					$('span[data-id=' + id + ']').html('No');
				} else if(idioma.enabled == 0) {
					idioma.enabled = 1;
					self.idiomas[id].enabled = 1;
					$('span[data-id=' + id + ']').html('Si');
				}

				self.changes.push(idioma);
			} else {
				let n = self.changes.length;
				let finish = false;
				let isInclude = false;
				let iInclude = null;
				for(let i = 0; i < n; i++) {
					if(!finish) {
						if(idioma.isocode == self.changes[i].isocode) {
							isInclude = true;
							finish = true;
							iInclude = i;
						}
					}
				}

				if(isInclude) {
					self.changes.splice(iInclude, 1);
					if(self.idiomas[id].enabled == 1) {
						self.idiomas[id].enabled = 0;
						$('span[data-id=' + id + ']').html('No');
					} else if(self.idiomas[id].enabled == 0) {
						self.idiomas[id].enabled = 1;
						$('span[data-id=' + id + ']').html('Si');
					}
				} else {
					if(idioma.enabled == 1) {
						idioma.enabled = 0;
						self.idiomas[id].enabled = 0;
						$('span[data_id=' + id + ']').html('No');
					} else if(idioma.enabled == 0) {
						idioma.enabled = 1;
						self.idiomas[id].enabled = 1;
						$('span[data-id=' + id + ']').html('Si');
					}
					self.changes.push(idioma);
				}
			}

			self.select = $('select').val();
			$('select').val(self.select);
		});
	},

	updateIdiomas() {
		let self = this;

		if(self.newDefaultLanguage != '') {
			if(self.defaultLanguage != '') {
				self.defaultLanguage.default = '0';
				self.changes.push(self.defaultLanguage);
			}
			self.changes.push(self.newDefaultLanguage);
		}

		let parameters = {
			idiomas: JSON.stringify(self.changes)
		};
		ajaxComunCallWithCallback('updateIdiomas', 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/idiomas.html', 'wrapper', IdiomasController);
			}
		});
	}
};