let RSCEditController = {
	user: null,
	idRSC: '',
	appRSC: '',
	systemRSC: '',
	objectRSC: '',
	languagesList: [],
	ckEditors: {},

	reset() {
		let self = this;

		self.user = null;
		self.idRSC = atob(sessionStorage.getItem('idRSC'));
		self.appRSC = atob(sessionStorage.getItem('appRSC'));
		self.systemRSC = atob(sessionStorage.getItem('systemRSC'));
		self.objectRSC = '';
		self.languagesList = atob(sessionStorage.getItem('languagesList')).split(',');
		self.ckEditors = {};
	},

	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.RSC466 + ' - ' + 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');

		self.requestRSC();

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

		// Collapse
		addEventArrowTableHeader();

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

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

	// Petición de los RSC
	requestRSC() {
		let self = this;

		let parameters = {
			rsc: self.idRSC
		};
		ajaxComunCallWithCallback('getRSC', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					if(ajaxReturn.result[i].app == self.appRSC && ajaxReturn.result[i].system == self.systemRSC) {
						self.objectRSC = ajaxReturn.result[i];
						break;
					}
				}

				// Render RSC
				self.renderForm();
			}
		});
	},

	renderForm() {
		let self = this;

		let RSCInputs = '';
		let size = self.languagesList.length;
		for(let i = 0; i < size; i++) {
			if(self.languagesList[i] == 'system' || self.languagesList[i] == 'country') {
				continue;
			}

			let htmlEditor = `<input id="${self.languagesList[i]}" type="text" class="form-control" value="${self.objectRSC[self.languagesList[i]]}" title="${self.objectRSC[self.languagesList[i]]}">`;

			if(self.languagesList[i] != 'idTenant' && self.languagesList[i] != 'idCPG') {
				htmlEditor = `<input id="${self.languagesList[i]}" type="text" class="ckEditor" name="editor${i}" value="${self.objectRSC[self.languagesList[i]]}">`;
			} 

			RSCInputs += `
				<div class="form-group">
					<label for="${self.languagesList[i]}">${self.languagesList[i]}</label>
					${htmlEditor}
				</div>
			`;
		}
		$('#RSCForm').html(RSCInputs);

		$('.ckEditor').each(function() {
			let id = $(this).attr('id');
			let value = $(this).val();
			ClassicEditor.create(document.querySelector('#' + id), {
				toolbar: ['bold', 'italic', 'underline']
			})
			.then(editor => {
				self.ckEditors[id] = editor;
				editor.setData(value);
			})
			.catch(error => {
				console.log('CKEditor Error');
			});
		});

		let url = window.location.href;
		if(self.objectRSC.system == '1') {
			$('#system').prop('checked', true);
			if(url.indexOf('localhost') == -1 && url.indexOf('sociallabs') == -1) {
				$('#system').prop('disabled', true);
				$('#country').prop('disabled', true);
				$('#RSCAplicacion').prop('disabled', true);
			}
		}
		if(self.objectRSC.country == '1') {
			$('#country').prop('checked', true);
		}
		if(self.objectRSC.app == '1') {
			$('#RSCAplicacion').prop('checked', true);
		}
	},

	applyEvents() {
		let self = this;

		stcmbackend.rsc.sharedEvents(self);

		let url = window.location.href;
		if(url.indexOf('localhost') != -1 || url.indexOf('sociallabs') != -1) {
			$('#system').prop('disabled', false);
		}

		// Editar entrada RSC
		$('#save').on('click', function() {
			self.editRSC();
		});
	},

	editRSC() {
		let self = this;

		let rsc = self.idRSC;

		let valueSys = $('#system').prop('checked') ? '1' : '0';
		let valueCou = $('#country').prop('checked') ? '1' : '0';
		let valueApl = $('#RSCAplicacion').prop('checked') ? '1' : '0';

		let parameters = {
			rsc: rsc,
			system: valueSys,
			country: valueCou,
			app: valueApl
		};

		let size = self.languagesList.length;
		for(let i = 0; i < size; i ++) {
			if(self.languagesList[i] == 'system' || self.languagesList[i] == 'country') {
				continue;
			}
			RSCKey = self.languagesList[i];

			// El value de los inputs de RSC por idioma se tienen que extraer de 
			// los objetos almacenados en la array self.ckEditors

			if(RSCKey in self.ckEditors) {
				RSCKeyParameters = RSCKey.toLowerCase();
				parameters[RSCKeyParameters] = self.ckEditors[RSCKey].getData().replace('<p>', '').replace('</p>', '');
			} else {
				RSCKeyParameters = RSCKey.toLowerCase();
				parameters[RSCKeyParameters] = $('#' + self.languagesList[i]).val().trim();
			}
		}

		ajaxComunCallWithCallback('updateRSC', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC466;
				let successContent = pf.const.language.RSC464;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!rsc';
			}
		});
	}
};