let HashtagsEditController = {
	user: null,
	idHashtag: '',
	parameters: [],

	reset() {
		let self = this;

		self.user = null;
		self.idHashtag = atob(sessionStorage.getItem('idHashtag'));
		self.parameters = [];
	},

	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.RSC2416 + ' - ' + pf.const.language.RSC225);

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

		let nav = `
			${createSubOptionSave(jsonsubopt.save)}
			${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');

		let parameters = {
			idHashtag: self.idHashtag
		};
		ajaxComunCallWithCallback('getHashtagByID', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				$('#name').val(ajaxReturn.result[0].text);
				$('#method').val(ajaxReturn.result[0].method);
				$('#description').val(ajaxReturn.result[0].description);
				$('#url').val(ajaxReturn.result[0].url);

				let size = ajaxReturn.result[0].params.length;
				for(let i = 0; i < size; i++) {
					let obj = {
						param: ajaxReturn.result[0].params[i].param,
						value: ajaxReturn.result[0].params[i].value
					};

					self.parameters.push(obj);
				}

				self.renderParameters();
			}
		});

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

		// Collapse
		addEventArrowTableHeader();

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

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

	applyEvents() {
		let self = this;

		// Añadir parámetro
		$('#newParameters').off().on('click', function() {
			let obj = {
				param: '',
				value: ''
			};
			self.parameters.push(obj);
			self.renderParameters();
		});

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

		// Editar hashtag
		$('#save').off().on('click', function() {
			self.updateHashtag();
		});
	},

	renderParameters() {
		let self = this;

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

				<tbody>
		`;

		let size = self.parameters.length;
		if(size < 1) {
			let obj = {
				param: '',
				value: ''
			};
			self.parameters.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			table += `
				<tr data-id="${i}">
					<td class="text-truncate">
						<span id="paramSpan${i}" class="d-none">${self.parameters[i].param}</span>
						<input id="paramInput${i}" type="text" class="form-control controlHash paramInput" value="${self.parameters[i].param}" title="${self.parameters[i].value}" data-index="${i}">
					</td>
					<td class="text-truncate">
						<span id="valueSpan${i}" class="d-none">${self.parameters[i].value}</span>
						<input id="valueInput${i}" type="text" class="form-control controlHash valueInput" value="${self.parameters[i].value}" title="${self.parameters[i].value}" data-index="${i}">
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteParam" data-index="${i}">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

		let parameters = $('#parametersTable').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '30px', orderable: false, targets: 2}
			],
			ordering: false,
			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('parametersTable');

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

		self.parametersEvents();
	},

	parametersEvents() {
		let self = this;

		// Input de nombre
		$('.paramInput').off().on('blur', function() {
			let index = $(this).data('index');
			let value = $(this).val().trim();
			self.parameters[index].param = value;
			$(this).val(value);
			$(this).attr('title', value);
			$('#paramSpan' + index).text(value);
		});

		// Input de valor
		$('.valueInput').off().on('blur', function() {
			let index = $(this).data('index');
			let value = $(this).val().trim();
			self.parameters[index].value = value;
			$(this).val(value);
			$(this).attr('title', value);
			$('#valueSpan' + index).text(value);
		});

		// Eliminar parámetro
		$('.deleteParam').off().on('click', function() {
			let index = $(this).data('index');
			self.parameters.splice(index, 1);
			self.renderParameters();
		});

		// 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);
		});
	},

	updateHashtag() {
		let self = this;

		let control = false;

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

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

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

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

		let parameters = {
			idHashtag: self.idHashtag,
			text: name,
			method: $('#method').val(),
			description: description,
			url: url,
			params : JSON.stringify(self.parameters)
		};
		ajaxComunCallWithCallback('updateHashtag', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC2416;
				let successContent = pf.const.language.RSC2423;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!hashtag';
			}
		});
	}
};