let DifusionEditController = {
	user: null,
	idlist: '',
	admin: '',
	activa: '',
	description: '',
	members: [],
	adminModal: null,
	crewObject: null,
	requestType: '',
	countryFilter: '',

	reset() {
		let self = this;

		self.user = null;
		self.idlist = atob(sessionStorage.getItem('dif_cont:idlist'));
		self.admin = atob(sessionStorage.getItem('dif_cont:admin'));
		self.activa = atob(sessionStorage.getItem('dif_cont:activa'));
		self.description = atob(sessionStorage.getItem('dif_cont:description'));
		self.members = [];
		self.adminModal = null;
		self.crewObject = null;
		self.requestType = '';
		self.countryFilter = atob(sessionStorage.getItem('dif_cont:country'));
	},

	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('.', '_');

		let adminName = atob(sessionStorage.getItem('dif_cont:adminName'));
		$('#admin').val(adminName);

		if(self.activa == 1) {
			$('#active').prop('checked', true);
		} else {
			$('#active').prop('checked', false);
		}

		$('#desc').val(self.description);
		$('#pais').val(self.countryFilter);

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

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

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

		let nav = `
			${createSubOptionSave(jsonsubopt.save)}
			${createSubOptionBack(jsonsubopt.back)}
		`;

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

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

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

		// Añadir textos
		$('#selectMembers').text(pf.const.language.RSC141);

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

		// Collapse
		addEventArrowTableHeader();

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

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

	applyEvents() {
		let self = this;

		stcmbackend.difusion.sharedEvents(self);

		// Administrador
		self.adminModal = new TableUsers(0, 'DifusionEditAdmin', self.countryFilter, '1', '1', '1');
		self.adminModal.surname = false;
		$('#searchAdmin').off().on('click', function() {
			self.requestType = 'admin';
			self.adminModal.setEvents();
		});

		// Ocultar cubo de basura
		let country = $('#pais').val();
		if(country != '') {
			$('#countryDelete').show();
		} else {
			$('#countryDelete').hide();
		}

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

		// Miembros
		self.crewObject = new TableUsers(1, 'DifusionEditCrew', self.countryFilter, '1', '1', '1');
		self.crewObject.surname = false;
		$('#searchMembers').off().on('click', function() {
			self.requestType = 'crew';
			self.crewObject.admin = self.admin;
			self.crewObject.setEvents();
		});

		// Guardar lista editada
		$('#saveDifusion').on('click', function() {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC78
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC12;
			let alertText = pf.const.language.RSC276;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.editDistributionList();
			}, function() {});
		});

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

		let parameters = {
			idlist: self.idlist
		};
		ajaxComunCallWithCallback('getDistributionListUsers', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				// Adecuación de usuarios para tableMembers
				for(let i = 0; i < size; i++) {
					let member = {
						email: ajaxReturn.result[i].emailUser,
						id: ajaxReturn.result[i].jidUser,
						nameUser: ajaxReturn.result[i].userNombre || ajaxReturn.result[i].idUser,
						userApellidos: ajaxReturn.result[i].userApellidos || '',
						userApellidos2: ajaxReturn.result[i].userApellidos2 || '',
					}
					self.members.push(member);
				}
				self.crewObject.members = self.members;
				tableMembers.setEvents(self.members, 'tableMembersUsers', 'editList');
			}
		});
	},

	clickEvents(data, dType = null) {
		let self = this;

		if(dType) {
			self.requestType = dType;
		}

		switch(self.requestType) {
			case 'admin':
				self.admin = data.id;
				$('#admin').val(data.nameUser + ' ' + data.userApellidos + ' ' + data.userApellidos2);
				break;
			case 'crew':
				self.members = data;
				tableMembers.setEvents(self.members, 'tableMembersUsers', 'editList');
				break;
			case 'removeMember':
				self.members.splice(data, 1);
				self.crewObject.members = self.members;
				tableMembers.setEvents(self.members, 'tableMembersUsers', 'editList');
				break;
				// Seleccionar país
			case 'country':
				self.countryFilter = data.isocode;
				self.adminModal.admin = null;
				self.adminModal.data = null;
				self.adminModal.country = self.countryFilter;
				self.crewObject.data = null;
				self.crewObject.country = self.countryFilter;
				$('#pais').val(data.isocode);
				$('#countryDelete').show();
				break;
		}
	},

	editDistributionList() {
		let self = this;

		let admin = self.admin;
		let description = $('#desc').val().trim();
		if(description === '') {
			$('#desc').addClass('is-invalid');
			$('[for="desc"]').addClass('is-invalid');
			let warningTitle = pf.const.language.RSC12;
			let warningContent = pf.const.language.RSC282;
			pf.utils.showInfoDialog(warningTitle, warningContent);
			return false;
		} else {
			$('#desc').removeClass('is-invalid');
			$('[for="desc"]').removeClass('is-invalid');
		}

		let activa = ($('#active').prop('checked') ? 1 : 0);
		let destinatarios = [];
		let size = self.members.length;
		for(let i = 0; i < size; i++) {
			destinatarios.push(self.members[i].id);
		}
		if(destinatarios.length == 0) {
			$('#members').addClass('is-invalid');
			$('#members-group').addClass('group-invalid');
			let warningTitle = pf.const.language.RSC12;
			let warningContent = pf.const.language.RSC283;
			pf.utils.showInfoDialog(warningTitle, warningContent);
			return false;
		}

		let parameters = {
			idlist: self.idlist,
			admin: admin,
			description: description,
			activa: activa,
			destinatarios: JSON.stringify(destinatarios),
			country: $('#pais').val()
		};
		ajaxComunCallWithCallback('updateDistributionList', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC12;
				let successContent = pf.const.language.RSC284;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!difusion';
			}
		});
	}
};