let ExclusionesWordcloudNewController = {
	language: '',
	wordsExcludedList: [],
	data: [],
	importExcludedWords: null,

	reset() {
		let self = this;

		self.language = sessionStorage['STCMBackEnd:lenguage'];
		self.wordsExcludedList = [];
		self.data = [];
		self.importExcludedWords = null;
	},

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

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

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

		// Opciones de header
		let jsonsubopt = {
			back: 'back',
			save: 'save',
			generateLayout: 'exportLayout',
			importLayout: 'importLayout'
		};

		let nav = `
			<div class="d-flex">
				${createSubOptionGenerateLayout(jsonsubopt.generateLayout)}
				${createSubOptionImportLayout(jsonsubopt.importLayout)}
				${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');
		$('#exportLayout').addClass('secondary-button');
		$('#importLayout').addClass('secondary-button');

		// Collapse
		addEventArrowTableHeader();

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

		self.applyEvents();

		stcmbackend.exclusionesWordcloud.loadLang(self);
		self.tableExclusions();
	},

	applyEvents() {
		let self = this;

		stcmbackend.exclusionesWordcloud.sharedEvents(self);

		// Guardar nueva entrada Exclusiones WordCloud
		$('#save').on('click', function() {
			// Si encuentra algún input con valor, guarda (Evitar mandar la array vacía)
			for(let i = 0; i < self.wordsExcludedList.length; i++) {
				if(self.wordsExcludedList[i].text !== '') {
					self.loadExclusion();
					break;
				}
			} 
		});

		// Añadir exclusión lista
		$('#newExclusion').off().on('click', function() {
			let text = '';
			self.wordsExcludedList.push(text);

			// Creación del HTML a incluir
			self.tableExclusions();
		});

		// Exportar layout vacío
		$('#exportLayout').click(function() {
			window.location = stcm.const.downloads + 'layout_exclusiones_wordcloud.xls';
		});

		// Importar excel
		$('#importLayout').click(function() {
			$('#inputFile').trigger('click');
		});

		// Detectar fichero subido
		$('#inputFile').change(function(evt) {
			self.uploadFile(evt);
		});
	},

	loadExclusion() {
		let self = this;

		let values = [];
		for(let index = 0; index < self.wordsExcludedList.length; index++) {
			if(self.wordsExcludedList[index] == '' || self.wordsExcludedList[index] == '') {
				continue;
			} else {
				values.push(self.language + '#' + self.wordsExcludedList[index]);
			}
		}

		// Introducimos las exclusiones anteriores
		for(let i = 0; i < self.data.length; i++) {
			values.push(self.data[i].lenguage + '#' + self.data[i].word);
		}

		let parameters = {
			values: JSON.stringify(values)
		};
		ajaxComunCallWithCallback('setWordsExcludedCloud', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC1838;
				let successContent = pf.const.language.RSC1862;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!exclusiones_wordcloud';
			}
		});
	},

	tableExclusions() {
		let self = this;

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

				<tbody>
		`;

		let size = self.wordsExcludedList.length;
		if(size < 1) {
			let text = '';
			self.wordsExcludedList.push(text);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			let text = self.wordsExcludedList[i].text;
			if(text == null) {
					text = self.wordsExcludedList[i];
			}

			table += `
				<tr data-id="${i}">
					<td class="text-truncate p-1">
						<span id="text${i}" class="d-none">${text}</span>
						<input id="textInput${i}" type="text" class="form-control textInput" value="${text}" title="${text}">
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteExclusion">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

		let tableReminders = $('#tableReminders').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '30px', targets: 1}
			],
			ordering: false,
			aaSorting: []
		});

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

		self.tableExclusionsEvents();
	},

	tableExclusionsEvents() {
		let self = this;

		// Input de texto
		$('.textInput').off().on('blur', function() {
			let index = $(this).attr('id').replace('textInput', '');
			let value = $(this).val();
			self.wordsExcludedList[index] = value + '';
		});

		// Eliminar recordatorio
		$('.deleteExclusion').off().on('click', function() {
			let index = $(this).parent().parent().data('id');
			self.wordsExcludedList.splice(index, 1);
			self.tableExclusions();
		});
	},

	uploadFile(evt) {
		let self = ExclusionesWordcloudNewController;

		addLoader();
		// Convertir excel a JSON
		var selectedFile = evt.target.files[0];
		var reader = new FileReader();
		reader.onload = function(event) {
			var data = event.target.result;
			var workbook = XLSX.read(data, {
				type: 'binary'
			});

			workbook.SheetNames.forEach(function(sheetName) {
				self.importExcludedWords = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
				self.importExcludedWords.forEach(element => {
					if(element.Exclusiones != null) {
						self.wordsExcludedList.push(element.Exclusiones);
					}
				});

				self.tableExclusions();
				removeLoader();
				$('#inputFile').val(null);
			})
		};

		/* reader.onerror = function(event) {
			console.error('File could not be read! Code ' + event.target.error.code);
		}; */

		reader.readAsBinaryString(selectedFile);
	}
};