import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { User } from '../core/entities';
import { LoginService } from './login.service';
import { AuthService } from '../core/services/auth.service';

@Component({
	selector: 'app-login',
	templateUrl: './login.component.html',
	styles: [`
		#form {
			padding-bottom: 10px;
		}

		.submitFormArea {
			line-height: 50px;
		}

		#errorMsg {
			max-height: 0;
			overflow: hidden;
			transition: max-height 0.5s ease-out;
			margin: 0;
		}
	`]
})
export class LoginComponent {
	model: User = new User('', '', '', '', '', null, null, '');
	loginError: string;

	constructor(
		private router: Router,
		private loginService: LoginService,
		private authService: AuthService
	) {}

	onSubmit(): void {
		this.loginService.login(this.model).subscribe((pUser: User) => {
			console.log('Login success.');
			this.authService.setAuthenticated(pUser);
			this.router.navigate(['/home']);
		}, (error) => {
			if (error.status === 401) {
				console.log('Login attempt failed.');
				this.setMessage('Adresse email ou mot de passe incorrect.');
			} else {
				console.error('Error during login attempt.', error);
				this.setMessage('Une erreur est survenue lors de la connexion.');
			}
		});
	}

	setMessage(message: string): void {
		this.loginError = message;

		const resultMsgDiv = document.getElementById('errorMsg');
		resultMsgDiv.style.maxHeight = '64px';

		setTimeout(() => {
			resultMsgDiv.style.maxHeight = '0px';
			setTimeout(() => {
				this.loginError = undefined;
			}, 550);
		}, 3000);
	}
}
