let PerfilController = {
	user: null,
	changeAvatar: false,
	file: null,
	maxSize: 0,

	setEvents() {
		let self = PerfilController;

		self.user = JSON.parse(sessionStorage['STCMBackEnd:user']);
		self.changeAvatar = false;
		self.file = null;
		self.maxSize = 0;

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

		// Nombre seccion
		$('#page-title').text(pf.const.language.RSC134);

		// Opciones de header
		let jsonsubopt = {
			save: 'btn-save',
			pass: 'btn-pass'
		};

		let nav = `
			${createSubOptionSave(jsonsubopt.save)}
			${createSubOptionChangePass(jsonsubopt.pass)}
		`;

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

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

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

		let avatar = sessionStorage['STCMBackEnd:user_avatar'];

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.maxSize = config.upload_max_filesize_bytes;

		// Imagen de avatar
		let attachedImg = stcm.const.downloads + 'tenants/0/avatar.jpg';
		if(avatar == 'true') {
			attachedImg = stcm.const.downloads + 'avatar/' + self.user.email + '/avatar.jpg?stamp=' + new Date().getTime();
		}

		$('#profile-avatar').attr('src', attachedImg);

		self.getIdiomas();
		self.loadLang();

		$(window).scrollTop(0);

		self.setInputs();

		$('#btn-save').click(function() {
			self.getInputs();
		});

		// Cambiar imagen
		$('#btn-image').click(function() {
			$('#imageUser').trigger('click');
		});

		$('#imageUser').change(function(evt) {
			self.file = evt.target.files[0];

			if(self.file.size > self.maxSize) {
				self.file = null;

				let alertTitle = pf.const.language.RSC134;
				let alertText = pf.const.language.RSC1337;
				pf.utils.showInfoDialog(alertTitle, alertText);
			} else {
				let inputFile = evt.target;
				let type = inputFile.files[0].type;
				let ext = type.split('/');
				if(ext[1] == 'png' || ext[1] == 'gif' || ext[1] == 'bmp' || ext[1] == 'jpg' || ext[1] == 'jpeg') {
					// Previsualizacion imagen
					let $imagenPrevisualizacion = $('#imageUser');
					let objectURL = URL.createObjectURL(self.file);
					$imagenPrevisualizacion.src = '';
					$imagenPrevisualizacion.src = objectURL;
					$('#profile-avatar').attr('src', $imagenPrevisualizacion.src)
					self.changeAvatar = true;
				} else {
					self.file = null;
					// Archivo a notificar
					let errorTitle = pf.const.language.RSC134;
					// Tipo de archivo no permitido
					let errorContent = pf.const.language.RSC507;
					pf.utils.showInfoDialog(errorTitle, errorContent);
				}
			}
		});

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

		// Contraseña
		$('#btn-pass').click(function() {
			setTimeout(function() {
				self.revelPass();
			}, 500);

			let content = `
				<div class="form-group">
					<label for="pass1" class="fw-500">${pf.const.language.RSC288}</label>
					<div class="input-group new-input-pass-style">
						<input id="pass1" type="password" class="form-control" name="pass1" aria-describedby="btn-users">
						<div class="input-group-append">
							<button id="btn-pass1" type="button" class="btn btn-outline-secondary">
								${stcmbackend.svg.eyeWithoutColor}
							</button>
						</div>
					</div>
				</div>

				<div class="form-group">
					<label for="pass2" class="fw-500">${pf.const.language.RSC289}</label>
					<div class="input-group new-input-pass-style">
						<input id="pass2" type="password" class="form-control" name="pass2" aria-describedby="btn-users">
						<div class="input-group-append">
							<button id="btn-pass2" type="button" class="btn btn-outline-secondary">
								${stcmbackend.svg.eyeWithoutColor}
							</button>
						</div>
					</div>
				</div>

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

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

			let alertTitle = pf.const.language.RSC287;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, content, objInfo, function() {
				self.changePassword();
			}, function() {});
		});

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

	// Mostrar Contraseña
	revelPass() {
		$('#btn-pass1').mouseup(function() {
			$('#pass1').attr('type', 'password');
		});

		$('#btn-pass1').mousedown(function() {
			$('#pass1').attr('type', 'text');
		});

		$('#btn-pass2').mouseup(function() {
			$('#pass2').attr('type', 'password');
		});

		$('#btn-pass2').mousedown(function() {
			$('#pass2').attr('type', 'text');
		});
	},

	changePassword() {
		let self = this;

		let pass1 = $('#pass1').val();
		let pass2 = $('#pass2').val();

		if(pass1 == pass2 && pass1 != '') {
			let parameters = {
				email: self.user.email,
				passwordAPI: pass1
			};
			ajaxComunCallWithCallback('resetPasswordAPIUser', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					let resetTitle = pf.const.language.RSC71;
					let resetContent = pf.const.language.RSC359;
					pf.utils.showInfoDialog(resetTitle, resetContent);
				}
			});
		} else {
			let alertTitle = pf.const.language.RSC287;
			let alertText = pf.const.language.RSC290;
			let alertBtn = pf.const.language.RSC78;
			pf.utils.showInfoDialog(alertTitle, alertText, alertBtn);
		}
	},

	getIdiomas() {
		let self = this;

		ajaxComunCallWithCallback('getIdiomas', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let idiomas = ajaxReturn.result;

				// Búsqueda de idiomas activos y creación de select
				let options = '';
				let size = idiomas.length;
				for(let i = 0; i < size; i++) {
					if(idiomas[i].enabled == 1) {
						options += `<option value="${idiomas[i].isocode}">${idiomas[i].descripcion}</option>`;
					}
				}

				$('#idioma').html(options);
				$('#idioma').val(self.user.lenguage);
			}
		}, false);
	},

	setInputs() {
		let self = this;

		// Datos perfil
		$('#name').val(self.user.name);
		$('#apellido1').val(self.user.apellido1);
		$('#apellido2').val(self.user.apellido2);
		$('#email').val(self.user.email);
		$('#empresa').val(self.user.empresa);
		$('#departamento').val(self.user.departamento);
		$('#pais').val(self.user.country);
	},

	getInputs() {
		let self = this;

		// Datos perfil
		self.user.name = $('#name').val();
		self.user.apellido1 = $('#apellido1').val();
		self.user.apellido2 = $('#apellido2').val();
		self.user.email = $('#email').val();
		self.user.empresa = $('#empresa').val();
		self.user.departamento = $('#departamento').val();
		let lenguage = $('#idioma').val();
		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));

		let parameters = {
			mustResetPass: self.user.mustResetPass,
			enabled: self.user.enabled,
			email: self.user.email,
			username: self.user.name,
			userapellidos: self.user.apellido1,
			userapellidos2: self.user.apellido2,
			empresa: self.user.empresa,
			departamento: self.user.departamento,
			file: self.file,
			changeAvatar: self.changeAvatar,
			country: $('#pais').val(),
			lenguage: lenguage,
			role: self.user.role,
			idTenant: self.user.idTenant,
			countries: allowedCountries
		};
		ajaxComunCallWithCallback('updateAPIUser', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let updateTitle = pf.const.language.RSC78;
				let updateContent = pf.const.language.RSC106;
				pf.utils.showInfoDialog(updateTitle, updateContent);
				let user = JSON.stringify(self.user);
				sessionStorage['STCMBackEnd:user'] = user;

				if(self.changeAvatar) {
					let attachedImg = stcm.const.downloads + 'avatar/' + self.user.email + '/avatar.jpg?stamp=' + new Date().getTime();

					$('#img-avatar').attr('src', attachedImg);
				}
			}
		});
	},

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

	onFilePickerClicked(e) {
		e.preventDefault();
		e.stopPropagation();
	},

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