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';
import { NotificationsComponent } from '../core/notifications/notifications.component';

@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, '');

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

	onSubmit(): void {
		this.loginService.login(this.model).subscribe((pUser: User) => {
			NotificationsComponent.success('Connexion réussie.');
			this.authService.setAuthenticated(pUser);
			this.router.navigate(['/myPosts']);
		}, (error) => {
			if (error === 'Unauthorized' || error.status === 401) {
				NotificationsComponent.error('Adresse email ou mot de passe incorrect.');
			} else {
				NotificationsComponent.error('Une erreur est survenue lors de la connexion.');
			}
		});
	}
}
