import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { MatSnackBar } from '@angular/material/snack-bar';
import { AuthService } from '../../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent {

  loginFailed = false;

  constructor(private authService: AuthService, private router: Router, private snackBar: MatSnackBar) {
  }

  loginForm = new FormGroup({
    email: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('', [Validators.required])
  });


  async login() {
    const email = this.loginForm.controls.email.value + '';
    const password = this.loginForm.controls.password.value + ''
    this.loginFailed = false;
    const success = await this.authService.login(email, password);

    if (success) {
      this.router.navigate(['/dashboard']).then();
    } else {
      this.loginFailed = true;
      this.snackBar.open('E-Mail oder Passwort ist falsch', undefined, {
        duration: 5000,
        panelClass: 'snackbar_error'
      });
    }
  }

}
