let VoiceAssistantEditController = {
	user: null,
	idDictionary: '',
	data: '',
	registers: [],
	hashData: null,
	btnRespIndex: '',
	loaders: {},
	idLineDelete: [],
	modalTableType: '',

	reset() {
		let self = this;

		self.user = null;
		self.idDictionary = atob(sessionStorage.getItem('idDictionary'));
		self.data = '';
		self.registers = [];
		self.hashData = null;
		self.btnRespIndex = '';
		self.loaders = {
			getVoiceassistantDictionaryById: false,
			getAllVoiceassistantDictionaryRegisters: false
		};
		self.idLineDelete = [];
		self.modalTableType = '';
	},

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

		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		let userMail = user.email;
		let user_split = userMail.split('@');
		self.user = user_split[0].replace('.', '_');

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

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

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

		let nav = `
			<div class="row mx-0">
				${createSubOptionImportDictionary(jsonsubopt.importDictionary)}
				${createSubOptionSave(jsonsubopt.save)}
			</div>

			${createSubOptionBack(jsonsubopt.back)}
		`;

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

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

		// Botones secundarios
		$('#back').addClass('secondary-button');
		$('#importDictionary').addClass('secondary-button');

		let parameters = {
			idDictionary: self.idDictionary
		};
		ajaxComunCallWithCallback('getVoiceassistantDictionaryById', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result[0];

				if(self.data.sistema == '1') {
					$('#system').prop('checked', true);
				}

				$('#name').val(self.data.description);
				$('#country').val(self.data.country);

				// Control de spinner
				self.loaders.getVoiceassistantDictionaryById = true;
				spinnerControl(self.loaders);
			}
		}, false);

		ajaxComunCallWithCallback('getAllVoiceassistantDictionaryRegisters', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					let obj = {
						descripcion: ajaxReturn.result[i].text,
						tipo: ajaxReturn.result[i].type,
						respuesta: ajaxReturn.result[i].answer,
						idHash: ajaxReturn.result[i].idHashtag,
						idLine: ajaxReturn.result[i].idLine,
						state: 'old',
						idDictionaryImp: '',
						idLineImp: ''
					};
					self.registers.push(obj);
				}

				self.renderRegisters();

				// Control de spinner
				self.loaders.getAllVoiceassistantDictionaryRegisters = true;
				spinnerControl(self.loaders);
			}
		}, false);

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

		// Collapse
		addEventArrowTableHeader();

		// Pintar texto de label
		changeLabelsColor();
	},

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

	applyEvents() {
		let self = this;

		// País
		let countryModal = new TableCountries(0, 'VoiceAssistantEditController');
		$('#searchCountry').off().on('click', function() {
			self.modalTableType = 'country';
			countryModal.setEvents();
		});

		// Añadir registro
		$('#newRegister').off().on('click', function() {
			let obj = {
				descripcion: '',
				tipo: 'texto',
				respuesta: '',
				idHash: '',
				idLine: '',
				state: 'new',
				idDictionaryImp: '',
				idLineImp: ''
			};
			self.registers.push(obj);
			self.renderRegisters();
		});

		// Cargar diccionarios
		let dictionaries = new TableDictionary('VoiceAssistantEditController', true);
		$('#importDictionary').click(function() {
			self.modalTableType = 'dictionaries';
			dictionaries.setEvents();
		});

		// Volver a diccionarios
		$('#back').off().on('click', function() {
			window.location.href = '#!voiceAssistant';
		});

		// Guardar nuevo diccionario
		$('#save').off().on('click', function() {
			self.updateVoiceassistantDictionary();
		});
	},

	renderRegisters() {
		let self = this;

		let table = `
			<table id="registersTable" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC438}">${pf.const.language.RSC438}</th>
						<th scope="col" title="${pf.const.language.RSC127}">${pf.const.language.RSC127}</th>
						<th scope="col" title="${pf.const.language.RSC2400}">${pf.const.language.RSC2400}</th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<thead class="filtersRegisters">
					<tr>
						<td>description</td>
						<td>type</td>
						<td>answer</td>
						<td>eye</td>
						<td>delete</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.registers.length;
		if(size < 1) {
			let obj = {
				descripcion: '',
				tipo: 'texto',
				respuesta: '',
				idHash: '',
				idLine: '',
				state: 'new',
				idDictionaryImp: '',
				idLineImp: ''
			};
			self.registers.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			let texto = '';
			let hashtag = ' d-none';
			if(self.registers[i].tipo === 'hashtag') {
				texto = ' d-none';
				hashtag = '';
			}

			let eye = '';
			if(self.registers[i].state !== 'new') {
				eye = `
					<button type="button" class="btn table-button main-color-text btnEyeSizeS botonSNM" data-idline="${self.registers[i].idLine}">
						${stcmbackend.svg.bigEyeWithoutColor}
					</button>
				`;
			}

			table += `
				<tr data-id="${i}">
					<td class="text-truncate">
						<span id="descSpan${i}" class="d-none">${self.registers[i].descripcion}</span>
						<input id="descInput${i}" type="text" class="form-control controlHash descInput" value="${self.registers[i].descripcion}" title="${self.registers[i].descripcion}" data-index="${i}">
					</td>
					<td class="text-truncate">
						<select id="tipo${i}" class="custom-select tipoSelect" data-index="${i}">
							<option value="texto" ${(self.registers[i].tipo === 'texto' ? 'selected' : '')}>${pf.const.language.RSC1210}</option>
							<option value="hashtag" ${(self.registers[i].tipo === 'hashtag' ? 'selected' : '')}>Hastag</option>
						</select>
					</td>
					<td class="">
						<span id="respSpan${i}" class="d-none">${self.registers[i].respuesta}</span>

						<!-- Input texto -->
						<input id="respInputText${i}" type="text" class="form-control controlHash respInput${texto}" value="${self.registers[i].respuesta}" title="${self.registers[i].respuesta}" data-index="${i}">

						<!-- Botón hashtag -->	
						<div id="respBotonHash${i}" class="form-group mb-0${hashtag}">
							<div class="input-group new-input-style">
								<input id="respInputHash${i}" type="text" disabled class="form-control" placeholder="" value="${self.registers[i].respuesta}" title="${self.registers[i].respuesta}">
								<div class="input-group-append">
									<button id="respBtn${i}" class="btn btn-outline-secondary btnResp" type="button" data-toggle="modal" data-target="#modalResp" data-index="${i}">
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td class="text-center">
						${eye}
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteResp" data-index="${i}">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

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

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

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

		let registersTable = $('#registersTable').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '100px', orderable: false, targets: 1},
				{width: '120px', orderable: false, targets: 3},
				{width: '30px', orderable: false, targets: 4}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1237,
				className: 'd-none',
				title: pf.const.language.RSC1237,
				exportOptions: {
					columns: [0, 1, 2],
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

		// Ocultar botones de tabla
		hideTableButtons('registersTable');

		// Apply the search
		applyTheSearch(registersTable, 'filtersRegisters');

		// Exportar tabla
		$('#exportRegister').off().on('click', function() {
			self.renderRegisters();
			$('#registrosTable .buttons-excel').trigger('click');
		});

		self.registersEvents();
	},

	registersEvents() {
		let self = this;

		// Input de descripción
		$('.descInput').off().on('blur', function() {
			let index = $(this).data('index');
			let value = $(this).val().trim();
			self.registers[index].descripcion = value;
			if(self.registers[index].idLine !== '') {
				self.registers[index].state = 'update';
			}
			$(this).val(value);
			$(this).attr('title', value);
			$('#descSpan' + index).text(value);
		});

		// Select de tipo
		$('.tipoSelect').off().on('change', function() {
			let index = $(this).data('index');
			let value = $(this).val();
			self.registers[index].tipo = value;
			if(self.registers[index].idLine !== '') {
				self.registers[index].state = 'update';
			}

			// Con el cambio de tipo se limpian los valores de respuesta
			self.registers[index].respuesta = '';
			$('#respSpan' + index).text('');
			$('#respInputText' + index).val('');
			$('#respInputText' + index).attr('title', '');
			$('#respInputHash' + index).val('');
			$('#respInputHash' + index).attr('title', '');

			if(value === 'texto') {
				$('#respInputText' + index).removeClass('d-none');
				$('#respBotonHash' + index).addClass('d-none');
			} else if(value === 'hashtag') {
				$('#respInputText' + index).addClass('d-none');
				$('#respBotonHash' + index).removeClass('d-none');
			}
		});

		// Input de respuesta
		$('.respInput').off().on('blur', function() {
			let index = $(this).data('index');
			let value = $(this).val().trim();

			// Comprobación de que no haya otra respuesta de texto igual
			let size = self.registers.length;
			for(let i = 0; i < size; i++) {
				if(value == self.registers[i].respuesta && self.registers[i].tipo == 'texto') {
					let successTitle = pf.const.language.RSC2395;
					let successContent = pf.const.language.RSC2472;
					pf.utils.showInfoDialog(successTitle, successContent);
					$(this).val('');
					return false;
				}
			}

			self.registers[index].respuesta = value;
			self.registers[index].idHash = '';
			if(self.registers[index].idLine !== '') {
				self.registers[index].state = 'update';
			}

			$(this).val(value);
			$(this).attr('title', value);
			$('#respSpan' + index).text(value);
		});

		// Botón de respuesta / hashtag
		$('.btnResp').off().on('click', function() {
			let index = $(this).data('index');
			self.btnRespIndex = index;

			if(!self.hashData) {
				ajaxComunCallWithCallback('getAllHashtag', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						self.hashData = ajaxReturn.result;

						self.renderAllHashtag();
					}
				});
			}
		});

		// Botón sinónimos / no match
		$('.botonSNM').off().on('click', function() {
			let idLine = $(this).data('idline');

			sessionStorage.setItem('idLine', btoa(idLine));
			window.location.href = '#!sinonimos';
		});

		// Eliminar registro de respuesta
		$('.deleteResp').off().on('click', function() {
			let index = $(this).data('index');
			if(self.registers[index].idLine !== '') {
				self.idLineDelete.push(self.registers[index].idLine);
			}
			self.registers.splice(index, 1);
			self.renderRegisters();
		});

		// Restricciones de carácter # por tecla para el Texto inicio de misión
		$('.controlHash').on('keypress', function(e) {
			// Parámetros: tecla, warningTitle, warningContent y pattern si no es el general
			let result = characterRestrictionsPerKey(e.keyCode, pf.const.language.RSC375, pf.const.language.RSC1999, /[^#]/i);

			return result;
		});

		// Restricciones del carácter # por pegado para el Texto inicio de misión
		$('.controlHash').on('paste', function() {
			// Parámetros: elemento, warningTitle, warningContent y pattern si no es el general
			characterRestrictionsPerPaste($(this), pf.const.language.RSC375, pf.const.language.RSC1999, /[#]/gi);
		});
	},

	renderAllHashtag() {
		let self = this;

		let table = `
			<table id="tableResp" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1210}">${pf.const.language.RSC1210}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
					</tr>
				</thead>

				<thead class="filtersHash">
					<tr>
						<td>texto</td>
						<td>descripción</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.hashData.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr class="c-pointer" data-id="${self.hashData[i].id}" data-text="${self.hashData[i].text}">
					<td class="text-truncate" title="${self.hashData[i].text}">${self.hashData[i].text}</td>
					<td class="text-truncate" title="${self.hashData[i].description}">${self.hashData[i].description}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

		// Ocultar botones de tabla
		hideTableButtons('tableResp');

		// Apply the search
		applyTheSearch(tableResp, 'filtersHash');

		$('#tableResp tbody').off().on('click', 'tr', function() {
			let respuesta = $(this).data('text');
			let idHash = $(this).data('id');

			self.registers[self.btnRespIndex].respuesta = respuesta;
			self.registers[self.btnRespIndex].idHash = idHash;
			if(self.registers[self.btnRespIndex].idLine !== '') {
				self.registers[self.btnRespIndex].state = 'update';
			}

			$('#respSpan' + self.btnRespIndex).text(respuesta);
			$('#respInputHash' + self.btnRespIndex).val(respuesta);
			$('#respInputHash' + self.btnRespIndex).attr('title', respuesta);

			$('#closeResp').trigger('click');
		});
	},

	updateVoiceassistantDictionary() {
		let self = this;

		let control = false;

		let description = $('#name').val().trim();
		if(description == '') {
			$('#name').addClass('is-invalid');
			$('[for="name"]').addClass('is-invalid');
			control = true;
		} else {
			$('#name').removeClass('is-invalid');
			$('[for="name"]').removeClass('is-invalid');
		}

		let country = $('#country').val();
		if(country == '') {
			$('#country').addClass('is-invalid');
			$('[for="country"]').addClass('is-invalid');
			control = true;
		} else {
			$('#country').removeClass('is-invalid');
			$('[for="country"]').removeClass('is-invalid');
		}

		if(control) {
			pf.utils.alerts.showCompleteAllFields();
			return false;
		}

		let parameters = {
			idDictionary: self.data.idDictionary,
			sistema: ($('#system').prop('checked') ? '1' : '0'),
			description: description,
			country: country,
			registers: JSON.stringify(self.registers),
			idLineDelete: JSON.stringify(self.idLineDelete)
		};
		ajaxComunCallWithCallback('updateVoiceassistantDictionary', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC2393;
				let successContent = pf.const.language.RSC2396;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!voiceAssistant';
			}
		});
	},

	clickEvents(data) {
		let self = this;

		switch(self.modalTableType) {
			// Seleccionar país
			case 'country':
				$('#country').val(data.isocode);
				break;

			// Seleccionar diccionario para importar
			case 'dictionaries':
				let parameters = {
					idDictionary: data.idDictionary
				};
				ajaxComunCallWithCallback('getAllVoiceassistantDictionaryRegisters', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						// Limpieza de array de registros si solo hay uno y está vacío
						if(self.registers.length == 1 && self.registers[0].descripcion == '' && self.registers[0].respuesta == '') {
							self.registers = [];
						}

						// Iteración inversa
						let size = (ajaxReturn.result.length - 1);
						for(let i = size; i >= 0; i--) {
							let obj = {
								descripcion: ajaxReturn.result[i].text,
								tipo: ajaxReturn.result[i].type,
								respuesta: ajaxReturn.result[i].answer,
								idHash: ajaxReturn.result[i].idHashtag,
								idLine: '',
								state: 'new',
								idDictionaryImp: data.idDictionary,
								idLineImp: ajaxReturn.result[i].idLine
							};
							// Añadir los nuevos registros al principio
							self.registers.unshift(obj);
						}
		
						self.renderRegisters();
					}
				});
				break;
		}
	}
};