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

@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 loginService: LoginService,
		private authService: AuthService,
		private router: Router
	) {}

	onSubmit(): void {
		this.loginError = undefined;

		this.loginService.login(this.model).subscribe(user => {
			this.authService.setToken(user.token);
			this.authService.setUser(user);
			this.router.navigate(['/myPosts']);
		}, error => {
			this.setMessage('Email ou password incorrect.');
		});
	}

	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);
	}
}
