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('', '', '', '', undefined, '');
  loginError;

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

  submitLogin(): void {
    this.loginService.login(this.model).subscribe(user => {
      this.authService.setToken(user.token);
      this.authService.setUser(user);
      this.router.navigate(['/server']);
    }, 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);
  }
}
