let UsuariosController = {
	countriesToSee: [],
	countriesToSeeDesc: '',
	registrationPermit: '0',

	reset() {
		let self = this;

		self.countriesToSee = [];
		self.countriesToSeeDesc = '';
		self.registrationPermit = sessionStorage['STCMBackEnd:addUsers'];
	},

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

		$('#usersCard').hide();

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

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

		// Opciones de header
		let jsonsubopt = {
			country: 'country',
			new: 'newUser',
			export: 'exportUsers',
			search: 'searchtUser'
		};

		let nav = `
			<div class="d-flex justify-content-end">
				${createSubOptionCountrySimple(jsonsubopt.country)}
				${createSubOptionSearch(jsonsubopt.search)}
				${createSubOptionNew(jsonsubopt.new)}
			</div>
		`;

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

		$('#newUser svg').css({'width': '24px', 'height': '24px'});

		// Botón principal
		$('#newUser').addClass('main-button');
		$('#newUser').removeClass('he-36');

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

		self.loadLanguage();
		self.applyEvents();

		// Control de alta de usuarios
		if(self.registrationPermit != '1') {
			$('#newUser').prop('disabled', true);
		}

		// Control de países permitidos por el administrador si solo hay uno
		let countries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let countriesDesc = atob(sessionStorage['STCMBackEnd:userCountriesDesc']);
		if(countries.length === 1 && sessionStorage['editUserCountry'] === undefined) {
			self.countriesToSee = countries;
			self.countriesToSeeDesc = countriesDesc;
			$('#country').val(self.countriesToSeeDesc);
			$('#country').attr('title', self.countriesToSeeDesc);

			// Cargar tabla
			$('#usersCard').show();
			self.loadUsers();
		}

		// Comprobar si se viene de editar un usuario
		if(sessionStorage['editUserCountry'] !== undefined) {
			self.countriesToSee = atob(sessionStorage['editUserCountry']);
			$('#country').val(self.countriesToSee);
			$('#country').attr('title', self.countriesToSee);
			sessionStorage.removeItem('editUserCountry');

			// Cargar tabla
			$('#usersCard').show();
			self.loadUsers();
		}

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	applyEvents() {
		let self = this;

		// País
		let countryModal = new TableCountries(1, 'users');
		$('#searchCountry').on('click', function() {
			countryModal.setEvents();
		});

		// Buscar usuario
		$('#searchtUser').click(function() {
			let content = `
				<div class="form-group">
					<label for="email" class="fw-500">${pf.const.language.RSC1788}</label>
					<input id="email" type="text" class="form-control" name="email">
				</div>

				<script>
					// Pintar texto de label
					changeLabelsColor();

					$('.jconfirm-open').on('keyup', function(e) {
						let code = (e.keyCode ? e.keyCode : e.which);
						if(code == 13) { //Enter keycode
							$('.new-style-accept').trigger('click');
						}
					});
				</script>
			`;

			let objInfo = {
				accept: {
					text: pf.const.language.RSC1787
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC1787;
			pf.utils.showInfoDialogCustomWidthAcceptCancelNewStyle(alertTitle, content, objInfo, '500px', function() {
				// Verificación de e-mail
				let email = $('#email').val().trim();
				if((email != '' && pf.utils.validateEmail(email))) {
					self.getUserData(email);
				} else {
					let alertTitle = pf.const.language.RSC1787;
					let alertText = pf.const.language.RSC1789;
					pf.utils.showInfoDialog(alertTitle, alertText);
				}
			}, function() {});
		});

		// Añadir usuario
		$('#newUser').click(function() {
			window.location.href = '#!usuarios/nuevo';
		});
	},

	loadUsers() {
		let self = this;

		// Cargar usuarios
		let users = new TableUsers(0, 'users', self.countriesToSee.toString(), 1, 1, 1);
		users.setEvents('tableUsers');
	},

	clickEvents(data) {
		if(data != '' && data != undefined) {
			sessionStorage['STCMBackEnd:editUser'] = btoa(JSON.stringify(data));
			window.location.href = '#!usuarios/editar';
		}
	},

	clickCountryEvents(data) {
		let self = this;

		self.countriesToSee = [];
		self.countriesToSeeDesc = '';

		let size = data.length;
		for(let i = 0; i < size; i++) {
			self.countriesToSee.push(data[i].isocode);
			self.countriesToSeeDesc += data[i].descripcion + ',';
		}
		self.countriesToSeeDesc = self.countriesToSeeDesc.substring(0, self.countriesToSeeDesc.length - 1);

		$('#country').val(self.countriesToSeeDesc);
		$('#country').attr('title', self.countriesToSeeDesc);

		sessionStorage.removeItem('editUserCountry');
		$('#usersCard').show();
		self.loadUsers();
	},

	getUserData(email) {
		let parameters = {
			email: email
		};
		ajaxComunCallWithCallback('getUserData', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.result[0] != '' && ajaxReturn.result[0] != undefined) {
					sessionStorage['STCMBackEnd:editUser'] = btoa(JSON.stringify(ajaxReturn.result[0]));
					window.location.href = '#!usuarios/editar';
				} else {
					let alertTitle = pf.const.language.RSC1787;
					let alertText = pf.const.language.RSC1790;
					pf.utils.showInfoDialog(alertTitle, alertText);
				}
			}
		});
	}
};