let AddonsEditController = {
	idAddOn: '',
	data: '',
	sections: [],
	sectionsOld: [],
	deeplinks: [],
	deeplinksOld: [],
	loaders: {},

	reset() {
		let self = this;

		self.idAddOn = atob(sessionStorage.getItem('idAddOn'));
		self.data = '';
		self.sections = [];
		self.sectionsOld = [];
		self.deeplinks = [];
		self.deeplinksOld = [];
		self.loaders = {
			getAllAddOns: false,
			getAllAddOnsSection: false
		};
	},

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

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

		// Añadir titulo
		$('#page-title').text(pf.const.language.RSC1246 + ' - ' + 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)
		$('#page-actions').html(nav);

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

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

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

		// Iniciar spinner
		addLoader();
		ajaxComunCallWithCallback('getAllAddOns', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let sizeA = ajaxReturn.response.length;
				for(let i = 0; i < sizeA; i++) {
					if(ajaxReturn.response[i].id == self.idAddOn) {
						self.data = ajaxReturn.response[i];

						let objectDL = ajaxReturn.response[i].deeplinks;
						for(let i = 0; i < objectDL.length; i++) {
							let obj = {
								id: objectDL[i].id,
								idOld: objectDL[i].id,
								description: objectDL[i].description,
								icon: objectDL[i].icon,
								file: '',
								publicPath: objectDL[i].publicPath
							};
							self.deeplinks.push(obj);
							let objOld = {
								id: objectDL[i].id,
								description: objectDL[i].description,
								icon: objectDL[i].icon,
								file: '',
								publicPath: objectDL[i].publicPath
							};
							self.deeplinksOld.push(objOld);
						}

						// AddOn a editar
						self.renderData();
						stcmbackend.addons.deeplinks.tableDeepLinks(self);
						break;
					}
				}

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

		let parameters = {
			idAddon: self.idAddOn
		};
		ajaxComunCallWithCallback('getAllAddOnsSection', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let sizeB = ajaxReturn.result.length;
				for(let i = 0; i < sizeB; i++) {
					let obj = {
						idSection: ajaxReturn.result[i].idSection,
						idSectionOld: ajaxReturn.result[i].idSection,
						description: ajaxReturn.result[i].description,
						section_icon: ajaxReturn.result[i].section_icon
					};
					self.sections.push(obj);
					let objOld = {
						idSection: ajaxReturn.result[i].idSection,
						description: ajaxReturn.result[i].description,
						section_icon: ajaxReturn.result[i].section_icon
					};
					self.sectionsOld.push(objOld);
				}

				stcmbackend.addons.sections.tableSections(self);

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

		// fontawesome-iconpicker
		$('#icons').iconpicker({
			fullClassFormatter(val) {
				return val;
			}
		});
		$('.iconpicker').css('width', '230px');

		// Collapse
		addEventArrowTableHeader();

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

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

		// TITLES
		$('.addTitle').attr('title', pf.const.language.RSC93);
		$('.exportTitle').attr('title', pf.const.language.RSC47);
	},

	applyEvents() {
		let self = this;

		// Métodos comunes
		stcmbackend.addons.applyEvents(self, 'editAddonsCountry');

		// Guardar AddOn
		$('#save').on('click', function() {
			self.updateAddOn();
		});
	},

	renderData() {
		let self = this;

		$('#name').val(self.data.addon_name);
		let icon = `<i class="${self.data.addon_icon}"></i>`;
		$('#icon-button').html(icon);
		$('#description').val(self.data.addon_description);
		$('#pais').val(self.data.country);
		if(self.data.country != '') {
			$('#countryDelete').show();
		}
		$('#path').val(self.data.addon_path);
		$('#url').val(self.data.addon_url);
		$('#function').val(self.data.addon_function);
		$('#parameters').val(self.data.addon_function_params);
		$('#variable').val(self.data.addon_var);
		if(self.data.enrolamiento == '1') {
			$('#register').prop('checked', true);
			$('#fullScreen').prop('disabled', true);
		}
		if(self.data.fullScreen == '1') {
			$('#fullScreen').prop('checked', true);
			$('#fullscreenWarning').removeClass('d-none');
		}
		if(self.data.addon_enabled == '1') {
			$('#enable').prop('checked', true);
		}
		if(self.data.gestiona_alert == '1') {
			$('#ownAlertManagement').prop('checked', true);
		}
	},

	updateAddOn() {
		let self = this;

		// Campos obligatorios 'addon_name' y 'addon_path'
		let addon_name_check = true;
		let addon_name = $('#name').val().trim();
		if(addon_name == '') {
			$('#name').addClass('is-invalid');
			$('[for="name"]').addClass('is-invalid');
			addon_name_check = false;
		} else {
			$('#name').removeClass('is-invalid');
			$('[for="name"]').removeClass('is-invalid');
			addon_name_check = true;
		}
		let addon_description = $('#description').val().trim();
		let addon_path_check = true;
		let addon_path = $('#path').val().trim();
		if(addon_path == '') {
			$('#path').addClass('is-invalid');
			$('[for="path"]').addClass('is-invalid');
			addon_path_check = false;
		} else {
			$('#path').removeClass('is-invalid');
			$('[for="path"]').removeClass('is-invalid');
			addon_path_check = true;
		}
		let addon_var = $('#variable').val().trim();
		let addon_function = $('#function').val().trim();
		let addon_function_params = $('#parameters').val().trim();
		let addon_enabled = ($('#enable').prop('checked') ? '1' : '0');
		let gestiona_alert = ($('#ownAlertManagement').prop('checked') ? '1' : '0');
		let enrolamiento = ($('#register').prop('checked') ? '1' : '0');
		let fullScreen = ($('#fullScreen').prop('checked') ? '1' : '0');
		let addon_url = $('#url').val().trim();
		let addon_icon = $('#icon-button').find('i').attr('class');

		if(!addon_name_check || !addon_path_check) {
			pf.utils.alerts.showCompleteAllFields();
			return false;
		}

		let parameters = {
			id: self.idAddOn,
			addon_name: addon_name,
			addon_description: addon_description,
			addon_path: addon_path,
			addon_var: addon_var,
			addon_function: addon_function,
			addon_function_params: addon_function_params,
			addon_enabled: addon_enabled,
			gestiona_alert: gestiona_alert,
			country: $('#pais').val(),
			addon_url: addon_url,
			addon_icon: addon_icon,
			secciones: JSON.stringify(self.sections),
			seccionesOld: JSON.stringify(self.sectionsOld),
			deeplinks: JSON.stringify(self.deeplinks),
			deeplinksOld: JSON.stringify(self.deeplinksOld),
			publicPath: stcm.const.downloads,
			enrolamiento: enrolamiento,
			fullScreen: fullScreen
		};

		let index = 0;
		self.deeplinks.forEach(element => {
			parameters['file' + index] = element.file;
			index = index + 1;
		});

		ajaxComunCallWithCallback('updateAddOn', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC1246;
				let successContent = pf.const.language.RSC1251;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!addons';
			}
		});
	},

	clickEvents(data) {
		$('#pais').val(data.isocode);
		$('#countryDelete').show();
	}
};