// Questo file fa parte di MyTown.
// MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
// i termini della GNU Affero General Public License come pubblicata dalla
// Free Software Foundation, versione 3.
// Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
// Copyright (C) Kondor Consulting & Services S.r.l.
// SPDX-License-Identifier: AGPL-3.0-or-later

import { Component, OnDestroy, OnInit, ApplicationRef, PipeTransform, Pipe, ViewChild } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
import { LoginService } from '../../providers/login.service';
import { ConfigService } from '../../providers/config.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Subscription, switchMap, timer } from 'rxjs';
import { Device } from '@capacitor/device';
import { AlertController, IonButton, IonInput } from '@ionic/angular';
import { Browser } from '@capacitor/browser';
import { Item } from '../../models/item';

import { Debounce } from '../../decorator/debounce.decorator';
import { PushService } from '../../providers/push.service';

@Component({
	selector: 'app-login',
	templateUrl: 'login.page.html',
	styleUrls: ['login.page.scss'],
	standalone: false,
})
export class LoginPage implements OnInit, OnDestroy {
	app_logo = '';
	viewPage = false;
	showErrBtn = false;
	capacitorPlatform = '';
	lstCountry: any = [];
	loginForm!: FormGroup;
	subscription!: Subscription;
	subscriptionCheckDevice!: Subscription;
	waitConfirmFromApp = false;
	user: any;
	response_check_app = '';
	viewInputToken = false;
	viewCounter = false;
	counter = 120;
	devicePlatform = '';
	model = '';
	tokenSmsVerified = false;
	usr_id = 0;
	firstname = '';
	lastname = '';
	displayname = '';
	phone = '';
	email = '';
	password = '';
	username = '';
	block_phone_field = false;
	block_mail_field = false;
	current_dial_code = '+39';
	check_privacy = false;
	codicefiscale = '';
	comuni: any = [];
	selectedComuneText = '';
	selectedComune: string[] = [];
	@ViewChild('verificaTokenSmsBTN', { static: false }) verificaTokenSmsBTN!: IonButton;
	verificaTokenSmsBTNdisabled = true;
	@ViewChild('digit') digit!: IonInput;
	checkUserRegistered: boolean = false;
	url_privacy = '';
	filtriModalOpen_Comuni = false;
	fundingModalOpen = false;
	/** Codice OTP del login (mostrato nelle 6 celle; `#digit` resta la fonte per la verifica). */
	otpCode = '';
	otpSlots = [0, 1, 2, 3, 4, 5];
	saveNominativoToken: any;
	tipo_registrazione = 'phone';
	arrayFunction: any[] = [];

	isRegistering = false;
	registrationStep = 1; // 1: initial form, 2: verification code, 3: user details
	registrationForm!: FormGroup;

	/** MyTown è pubblica: dal login si può tornare alla bacheca (sola visualizzazione). */
	get isMyTown(): boolean {
		return this.config.isMyTown();
	}

	backToBacheca() {
		this.router.navigate(['/bakeka']);
	}

	isResetPassword = false;
	type_username = 1;
	sessionRegisterUUID = '';
	viewInputTokenPhone = false;
	viewCounterPhone = false;
	viewInputTokenMail = false;
	viewCounterMail = false;
	phone_validated = false;
	mail_validated = false;
	counterPhone = 120;
	counterMail = 120;
	block_username_option = false;

	/** Fase corrente dello step 3 di registrazione, derivata dai flag esistenti
	 *  (1 = dati, 2 = verifica email/OTP, 3 = password). Nessun side-effect. */
	get regPhase(): number {
		if (this.mail_validated) return 3;
		if (this.viewInputTokenMail) return 2;
		return 1;
	}

	constructor(private login: LoginService, private config: ConfigService, private pushService: PushService, private formBuilder: FormBuilder, private router: Router, private appRef: ApplicationRef, private location: Location, private alertController: AlertController) {
		this.initializeForms();
	}

	initializeForms() {
		this.registrationForm = this.formBuilder.group({
			username: [''],
			password: [''],
		});
		this.updateFormValidation();
	}

	updateFormValidation() {
		const usernameField = this.registrationForm.get('username');
		const passwordField = this.registrationForm.get('password');

		usernameField?.clearValidators();
		passwordField?.clearValidators();

		usernameField?.clearValidators();
		passwordField?.clearValidators();

		usernameField?.updateValueAndValidity({ emitEvent: false });
		passwordField?.updateValueAndValidity({ emitEvent: false });
	}

	ngOnInit() {
		this.appRef.tick();

		if (this.subscription) {
			this.subscription.unsubscribe();
		}

		if (this.subscriptionCheckDevice) {
			this.subscriptionCheckDevice.unsubscribe();
		}

		this.capacitorPlatform = this.config.platform;
		this.url_privacy = this.config.url_privacy;

		fetch('./assets/config/country.json')
			.then((res) => res.json())
			.then((json) => {
				this.lstCountry = json;
			});
	}

	ionViewDidEnter() {
		this.block_phone_field = false;
		this.block_mail_field = false;
		this.phone_validated = false;
		this.mail_validated = false;
		this.block_username_option = false;
		this.setTipoRegistrazione();

		if (this.config.getUser()) {
			if (this.config.getUser().token) {
				let token = this.config.getUser().token;
				let token_will_exipre = new Date(parseInt(JSON.parse(atob(token.substring(token.indexOf('.') + 1, token.lastIndexOf('.')))).exp + '000'));
				if (token_will_exipre.getTime() - new Date().getTime() < 0 && this.config.getUser()?.usr_id != 0) {
					localStorage.clear();
				} else {
					this.router.navigate([this.config.getLandingRoute()]);
					return;
				}
			}
		}

		this.deviceInfo();
		this.verifyUser();
	}

	setTipoRegistrazione() {
		this.loginForm = this.formBuilder.group({
			username: ['', [Validators.required, Validators.pattern('(^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$)|(^[0-9]+$)')]],
			password: ['', [Validators.required]],
		});

		// Update registration form validation if in registration mode
		if (this.isRegistering) {
			this.updateFormValidation();
		}
	}

	/** Tiene solo le cifre nel codice OTP del login (max 6) per le celle. */
	onOtpInput(event: any): void {
		const digits = ((event?.detail?.value ?? '') as string).replace(/\D/g, '').slice(0, 6);
		this.otpCode = digits;
	}

	/** Porta il focus sull'input OTP nascosto (tap sulle celle). */
	focusOtp(): void {
		this.digit?.setFocus();
	}

	nextDigit(event?: any, nextiput?: any, previousinpit?: any) {
		if (nextiput) {
			if (event.keyCode == 8) {
				previousinpit.setFocus();
			} else if (event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || event.keyCode == 51 || event.keyCode == 52 || event.keyCode == 53 || event.keyCode == 54 || event.keyCode == 55 || event.keyCode == 56 || event.keyCode == 57) {
				nextiput.setFocus();
			} else {
				event.target.value = '';
			}
		}
	}

	ngOnDestroy() {
		if (this.subscription) {
			this.subscription.unsubscribe();
		}

		if (this.subscriptionCheckDevice) {
			this.subscriptionCheckDevice.unsubscribe();
		}
	}

	verifyUser() {
		this.verifyUser2();
	}
	async verifyUser2() {
		let data: any = {};
		data.id_device = (await Device.getId()).identifier;

		if (data.id_device) {
			this.viewPage = true;
			this.showErrBtn = false;
		} else {
			this.showErrBtn = true;
			console.error('No id device found...');
		}
		this.appRef.tick();
	}

	private async getDeviceId(): Promise<string> {
		return (await Device.getId()).identifier;
	}

	@Debounce(500)
	loginSubmit() {
		if (!this.loginForm.valid) {
			this.config.presentToastError('Inserire un numero di telefono valido o una mail valida');
		}

		let data: any = {};
		data.usr_username = this.loginForm.value.username;
		data.usr_password = this.loginForm.value.password;

		this.subscription = timer(0, 1000)
			.pipe(switchMap(async () => this.verifyTimerSms()))
			.subscribe();
		this.inviaTokenSms(data);
	}

	verifyConfirmFromApp() {
		this.login.login_check_app(this.user).subscribe((res) => {
			switch (res.mode_verifica) {
				case 'DEL':
					this.subscription.unsubscribe();
					this.response_check_app = 'DEL';
					break;
				case 'KO':
					this.subscription.unsubscribe();
					this.response_check_app = 'KO';
					break;
				case 'OK':
					this.subscription.unsubscribe();
					res.mode_verifica = 'APP';
					localStorage.setItem('currentUser', JSON.stringify(res));

					this.setUserLastAccess();
					this.tokenSmsVerified = false;
					this.viewInputToken = false;
					this.checkUserRegistered = false;
					let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
						let r = (Math.random() * 16) | 0,
							v = c == 'x' ? r : (r & 0x3) | 0x8;
						return v.toString(16);
					});

					this.login.set_reload(true);
					this.pushService.subscribeToBackend();
					this.router.navigate([this.config.getLandingRoute(), { refresh: uuid }]);

					break;
			}
		});
	}

	@Debounce(500)
	async inviaTokenSms(data: any) {
		data.id_device = await this.getDeviceId();

		let rs = this.isRegistering ? 1 : 0;

		data.mode_verifica = 'it';
		if (/^[0-9]+$/.test(data.usr_username)) {
			data.usr_username = '+39' + data.usr_username;
		}
		this.login.send_sms(data, this.checkUserRegistered, rs).subscribe(
			(res) => {
				if (res.status == 'failure') {
					if (res.data && res.data == 'ERR8425') {
						//Utente registrato
						this.config.presentToastError(res.message);
						this.cancelRegistration();
						this.counter = 0;
						return;
					} else if (res.data && res.data == 'ERR8725') {
						//Utente registrato
						this.config.presentToastError(res.message);
						this.cancelRegistration();
						this.counter = 0;
						return;
					} else if (res.data && res.data == 'ERR8925') {
						//Utente registrato
						this.config.presentToastError(res.message);
						this.cancelRegistration();
						this.counter = 0;
						return;
					}
				}

				if (res.res == '1') {
					if (/^\+39[0-9]+$/.test(data.usr_username)) {
						this.config.presentToastSuccess("E' stato inviato un messaggio al numero indicato con il codice di conferma");
					} else {
						this.config.presentToastSuccess("E' stato inviato un messaggio alla mail indicata con il codice di conferma");
					}
					this.viewInputToken = true;
					this.viewCounter = true;
					setTimeout(() => {
						console.log(this.digit);

						this.digit.setFocus();
					}, 1000);
				} else {
					this.config.presentToastSuccess("L' utente non risulta registrato");
					this.counter = 0;
					this.appRef.tick();
				}
			},
			(err) => () => {
				this.counter = 0;
				console.log('errore');
			},
		);
	}

	verifyTimerSms() {
		if (this.counter === 0) {
			this.subscription.unsubscribe();
			this.counter = 120;
			this.viewCounter = false;
			this.viewInputToken = false;
			this.appRef.tick();
			//this.tipo_registrazione_disabled = false;
			return;
		}
		--this.counter;
		this.appRef.tick();
	}

	appClose() {
		this.subscription.unsubscribe();
		this.waitConfirmFromApp = false;
		this.user.mode_verifica = '2FAT';
	}

	refresh() {
		window.location.reload();
	}

	async verificaTokenSms() {
		let data: any = {};
		data.usd_id_device = await this.getDeviceId();
		data.usd_device_type = this.devicePlatform;
		data.usd_language = 'it';
		data.usd_model = this.model;
		let tokenSms = this.digit.value?.toString();

		if (tokenSms && tokenSms.length == 6) {
			// Get values from the appropriate form based on mode
			let number;
			if (this.isRegistering) {
				number = this.registrationForm.value.username;
			} else {
				number = this.loginForm.value.username;
			}

			if (/^[0-9]+$/.test(number)) {
				number = '+39' + number;
			}
			this.login.check_token_sms(data, number, tokenSms, true).subscribe((res) => {
				if (res) {
					if (res.usr_codicefiscale === 'X') {
						this.isRegistering = true;
						this.registrationStep = 3;
						this.viewPage = true;
						/* SE REGISTRA I DATI SONO VALIDATI DI DEFAULT*/
						this.phone_validated = true;
						this.mail_validated = true;
						if (/^\+39[0-9]+$/.test(res.usr_username)) {
							this.type_username = 1;
						} else {
							this.type_username = 2;
						}
						this.block_username_option = true;
						this.block_phone_field = true;
						this.block_mail_field = true;
						this.imposta_saveNominativo(res);
					} else {
						localStorage.setItem('currentUser', JSON.stringify(res));
						this.tokenSmsVerified = false;
						this.viewInputToken = false;
						this.checkUserRegistered = false;

						this.setUserLastAccess();
						this.login.set_reload(true);
						this.pushService.subscribeToBackend();
						this.router.navigate([this.config.getLandingRoute(), { refresh: true }]);
					}
				} else {
					this.config.presentToastError('Codice di autenticazione errato');
				}
			});
		}
		tokenSms = '';
	}

	/*!this.codicefiscale ||*/
	saveNominativo() {
		if (!this.firstname || !this.lastname || !this.displayname || !this.phone || !this.email || !this.password || !this.check_privacy) {
			if (!this.firstname) {
				this.config.presentToastError('Inserisci il nome');
				return;
			}
			if (!this.lastname) {
				this.config.presentToastError('Inserisci il cognome');
				return;
			}
			if (!this.displayname) {
				this.config.presentToastError('Inserisci il nome da visualizzare');
				return;
			}
			if (!this.phone) {
				this.config.presentToastError('Inserisci il numero di telefono');
				return;
			}
			if (!this.email) {
				this.config.presentToastError('Inserisci la mail');
				return;
			}
			if (!this.password) {
				this.config.presentToastError('Inserisci la password');
				return;
			}
			if (!this.check_privacy) {
				this.config.presentToastError('Accetta i nostri termini & condizioni');
				return;
			}
			this.config.presentToastError('Inserisci i tuoi dati');
			return;
		}

		if (this.phone && !this.phone.startsWith('+39')) {
			this.phone = this.current_dial_code + this.phone;
		}

		this.login.save_nominativo(this.firstname, this.lastname, this.displayname, this.phone, this.email, this.password, this.codicefiscale, this.saveNominativoToken).subscribe((res) => {
			this.config.presentToastSuccess('Registrazione avvenuta con successo');
			//MI INIZIO gestione registrazione tramite link
			this.saveNominativoToken.authorities = res.authorities;
			this.saveNominativoToken.usr_privacy = res.usr_privacy;
			this.saveNominativoToken.usr_lastname = res.usr_lastname;
			this.saveNominativoToken.usr_firstname = res.usr_firstname;
			this.saveNominativoToken.usr_displayname = res.usr_displayname;
			this.saveNominativoToken.usr_phone = res.usr_phone;
			this.saveNominativoToken.usr_mail = res.usr_mail;
			this.saveNominativoToken.usr_codicefiscale = res.usr_codicefiscale;
			//MI FINE gestione registrazione tramite link
			localStorage.setItem('currentUser', JSON.stringify(this.saveNominativoToken));

			this.tokenSmsVerified = false;
			this.viewInputToken = false;
			this.checkUserRegistered = false;

			this.setUserLastAccess();
			this.login.set_reload(true);
			this.pushService.subscribeToBackend();
			this.router.navigate([this.config.getLandingRoute(), { refresh: true }]);
		});
	}

	async deviceInfo() {
		const device = await Device.getInfo();
		this.devicePlatform = device.platform;
		this.model = device.model;
	}

	imposta_saveNominativo(res: any) {
		this.usr_id = res.usr_id;
		this.firstname = res.usr_firstname;
		this.lastname = res.usr_lastname;
		this.displayname = res.usr_displayname;
		this.phone = res.usr_phone.replace(/^\+39/, '');
		this.email = res.usr_mail;
		this.check_privacy = false;

		this.login.comuni().subscribe((res) => {
			res.forEach((element: any) => {
				let d: Item = { text: element.denominazione, value: element.codicefiscale };
				this.comuni.push(d);
			});
		});
	}

	sel_comune(event: any) {
		this.selectedComune = event;
		this.selectedComuneText = '';
		if (this.selectedComune.length > 0) {
			this.codicefiscale = this.selectedComune[0];
			this.selectedComuneText = this.comuni.find((x: any) => x.value === this.codicefiscale).text;
		}
		this.setOpen_Comuni(false);
		this.appRef.tick();
	}

	setIsWebAccess() {
		this.checkUserRegistered = true;
	}

	openPrivacy() {
		const openCapacitorSite = async () => {
			await Browser.open({ url: this.url_privacy });
		};
		openCapacitorSite();
	}

	setOpen_Comuni(isOpen: boolean) {
		this.filtriModalOpen_Comuni = isOpen;
	}

	setUserLastAccess() {
		this.login.setUserLastAccess().subscribe();
	}

	precompiledDisplayname() {
		if (this.firstname && this.lastname) {
			this.displayname = this.firstname + ' ' + this.lastname;
		}
	}

	onCountryChange(event: any) {
		this.current_dial_code = event.detail.value;
	}

	goBack(): void {
		this.location.back();
	}

	isValidEmail(email: string): boolean {
		if (!email || email.trim() === '') {
			return false;
		}
		const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
		return emailPattern.test(email);
	}

	startRegistration() {
		this.isRegistering = true;
		this.registrationStep = 3;
		this.sessionRegisterUUID = crypto.randomUUID();
		// Username sarà sempre email
		this.type_username = 2;
		// Telefono non richiesto per la registrazione
		this.phone_validated = true;
	}

	cancelRegistration() {
		this.isRegistering = false;
		this.registrationStep = 1;
		this.viewInputToken = false;
		this.tokenSmsVerified = false;
	}

	cancelTokenRegistration(type: string) {
		switch (type) {
			case 'phone':
				this.viewInputTokenPhone = false;
				this.block_phone_field = false;
				this.phone_validated = false;
				break;
			case 'mail':
				this.viewInputTokenMail = false;
				this.block_mail_field = false;
				this.mail_validated = false;
				break;
		}

		this.registrationStep = 3;
	}

	startResetPassword() {
		this.isRegistering = true;
		this.registrationStep = 1;
		this.registrationForm.reset({
			username: '',
		});
		this.isResetPassword = true;
	}

	cancelResetPassword() {
		this.cancelRegistration();
		this.isResetPassword = false;
	}

	submitRegistration() {
		let data: any = {};
		if (!this.isResetPassword) {
			// Set registration flag
			data.isRegistration = true;

			data.usr_username = this.loginForm.value.username;

			this.subscription = timer(0, 1000)
				.pipe(switchMap(async () => this.verifyTimerSms()))
				.subscribe();

			this.inviaTokenSms(data);
			this.registrationStep = 2;
		} else {
			data.usr_username = this.registrationForm.value.username;
			if (/^[0-9]+$/.test(data.usr_username)) {
				data.usr_username = '+39' + data.usr_username;
			}
			this.sendMailresetPasswordUser(data);
		}
	}

	sendMailresetPasswordUser(user: any) {
		this.login.sendMailresetPasswordUser(user).subscribe((res: any) => {
			if (res > 0) {
				this.alertMailsent(user.usr_username);
			}
		});
	}

	async alertMailsent(usr_username: string) {
		let tipo_registrazione = '';
		const messages: any = {
			phone: {
				header: 'Sms Inviato con successo',
				message: 'Ti è appena stato inviato un SMS per resettare la password.',
			},
			email: {
				header: 'Email Inviata con successo',
				message: 'Ti è appena stata inviata una mail per resettare la password. Controlla la tua casella di posta.',
			},
		};

		if (/^[0-9]+$/.test(usr_username)) {
			tipo_registrazione = 'phone';
		} else {
			tipo_registrazione = 'email';
		}

		const { header, message } = messages[tipo_registrazione] || messages.email;

		const alert = await this.alertController.create({
			header,
			message,
			buttons: [{ text: 'Conferma', handler: () => this.cancelResetPassword() }],
		});

		await alert.present();
	}

	sendTokenRegistration(type: string, data: string, dial_code?: string) {
		if (type === 'phone' && data.length < 8) {
			this.config.presentToastError('Inserire un numero di telefono valido');
			return;
		}

		// Validazione email
		if (type === 'mail' && !this.isValidEmail(data)) {
			this.config.presentToastError('Inserire un indirizzo email valido');
			return;
		}

		let user: any = {};
		switch (type) {
			case 'phone':
				let phonenumber = data.replaceAll(' ', '').replaceAll('-', '').replaceAll('(', '').replaceAll(')', '');
				user.usr_username = dial_code + phonenumber;
				break;
			case 'mail':
				user.usr_username = data;
				break;
		}

		user.isRegistration = true;

		user.usr_firstname = this.firstname;
		user.lastname = this.lastname;
		user.usr_displayname = this.displayname;

		this.inviaTokenRegistration(type, user);
	}

	verifyTimerPhoneRegistration() {
		if (this.counterPhone === 0) {
			this.subscription.unsubscribe();
			this.counterPhone = 120;
			this.viewCounterPhone = false;
			this.viewInputTokenPhone = false;
			this.appRef.tick();
			return;
		}
		--this.counterPhone;
		this.appRef.tick();
	}

	verifyTimerMailRegistration() {
		if (this.counterMail === 0) {
			this.subscription.unsubscribe();
			this.counterMail = 120;
			this.viewCounterPhone = false;
			this.viewInputTokenPhone = false;
			this.appRef.tick();
			return;
		}
		--this.counterMail;
		this.appRef.tick();
	}

	@Debounce(500)
	async inviaTokenRegistration(type: string, user: any) {
		user.id_device = await this.getDeviceId();

		let rs = this.isRegistering ? 1 : 0;

		user.mode_verifica = 'it';
		this.login.send_token_registration(user, rs, this.sessionRegisterUUID).subscribe(
			(res: any) => {
				if (res.status == 'failure') {
					if (res.data && res.data == 'ERR8425') {
						//Utente registrato
						this.config.presentToastError(res.message);
						this.cancelTokenRegistration(type);
						return;
					} else if (res.data && res.data == 'ERR8725') {
						//Utente registrato
						this.config.presentToastError(res.message);
						this.cancelTokenRegistration(type);
						return;
					}

					switch (type) {
						case 'phone':
							this.counterPhone = 0;
							break;
						case 'mail':
							this.counterMail = 0;
							break;
					}
				}

				if (res.res == '1') {
					this.subscription = timer(0, 1000)
						.pipe(
							switchMap(async () => {
								switch (type) {
									case 'phone':
										this.verifyTimerPhoneRegistration();
										break;
									case 'mail':
										this.verifyTimerMailRegistration();
										break;
								}
							}),
						)
						.subscribe();
					if (type === 'phone') {
						this.block_phone_field = true;
						this.viewInputTokenPhone = true;
						this.viewCounterPhone = true;
						this.config.presentToastSuccess("E' stato inviato un messaggio al numero indicato con il codice di conferma");
					} else {
						this.block_mail_field = true;
						this.viewInputTokenMail = true;
						this.viewCounterMail = true;
						this.config.presentToastSuccess("E' stato inviato un messaggio alla mail indicata con il codice di conferma");
					}
					//this.tipo_registrazione_disabled = true;
					//Setto il focus sul primo input dopo 1000ms
					setTimeout(() => {
						console.log(this.digit);

						this.digit.setFocus();
					}, 1000);
				} else {
					this.config.presentToastSuccess("L' utente non risulta registrato");
					switch (type) {
						case 'phone':
							this.counterPhone = 0;
							break;
						case 'mail':
							this.counterMail = 0;
							break;
					}
					this.appRef.tick();
				}
			},
			(err: any) => () => {
				switch (type) {
					case 'phone':
						this.counterPhone = 0;
						break;
					case 'mail':
						this.counterMail = 0;
						break;
				}
				console.log('errore');
			},
		);
	}

	verificaTokenRegistration(type: string, phone_mail: string, dial_code?: string) {
		let tokenSms = this.digit.value?.toString();

		if (tokenSms && tokenSms.length == 6) {
			let number;
			if (this.isRegistering) {
				switch (type) {
					case 'phone':
						let phonenumber = phone_mail.replaceAll(' ', '').replaceAll('-', '').replaceAll('(', '').replaceAll(')', '');
						number = dial_code + phonenumber;
						break;
					case 'mail':
						number = phone_mail;
						break;
				}
			}

			this.login.check_token_registration(number!, tokenSms, this.sessionRegisterUUID).subscribe((res) => {
				if (res) {
					if (res > 0) {
						switch (type) {
							case 'phone':
								this.phone_validated = true;
								this.viewInputTokenPhone = false;
								this.viewCounterPhone = false;
								this.config.presentToastSuccess('Telefono validato correttamente');
								break;
							case 'mail':
								this.mail_validated = true;
								this.viewInputTokenMail = false;
								this.viewCounterMail = false;
								this.config.presentToastSuccess('Email validata correttamente');
								break;
						}
					}
				} else {
					this.config.presentToastError('Codice di autenticazione errato');
				}
			});
		}
		tokenSms = '';
	}

	registerUser() {
		if (!this.firstname || !this.lastname || !this.displayname || !this.email || (!this.password && !this.block_username_option)) {
			if (!this.firstname) {
				this.config.presentToastError('Inserisci il nome');
				return;
			}
			if (!this.lastname) {
				this.config.presentToastError('Inserisci il cognome');
				return;
			}
			if (!this.displayname) {
				this.config.presentToastError('Inserisci il nome da visualizzare');
				return;
			}
			if (!this.email) {
				this.config.presentToastError('Inserisci la mail');
				return;
			}
			if (!this.password && !this.block_username_option) {
				this.config.presentToastError('Inserisci la password');
				return;
			}
			this.config.presentToastError('Inserisci i tuoi dati');
			return;
		}

		// Username è sempre l'email
		this.username = this.email;

		const phoneToSend = this.phone && this.phone.trim() !== '' ? (this.phone.startsWith('+') ? this.phone : this.current_dial_code + this.phone) : '';

		this.login.register_user(this.usr_id, this.username, this.firstname, this.lastname, this.displayname, phoneToSend, this.email, this.password, this.codicefiscale, this.sessionRegisterUUID).subscribe((res) => {
			this.config.presentToastSuccess('Registrazione avvenuta con successo');
			this.viewInputTokenPhone = false;
			this.viewCounterPhone = false;
			this.viewInputTokenMail = false;
			this.viewCounterMail = false;
			this.phone_validated = false;
			this.mail_validated = false;
			this.checkUserRegistered = false;
			this.login.set_reload(true);
			this.router.navigate(['/login', { refresh: true }]);
		});
	}
}

@Pipe({
	name: 'formatTime',
	standalone: false,
})
export class FormatTimePipe implements PipeTransform {
	transform(value: number): string {
		const minutes: number = Math.floor(value / 60);
		return ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2);
	}
}
