import { Component, OnInit } from '@angular/core';
import { LoginInfo } from '../auth/login-info';
import { AuthService } from '../auth/auth.service';
import { TokenStorageService } from '../auth/token-storage.service';
import { MatSnackBar } from "@angular/material/snack-bar";
import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import { Router } from "@angular/router";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  form: FormGroup = new FormGroup({
    email: new FormControl(''),
    password: new FormControl(''),
  });
  token?: string;
  isLoggedIn = false;
  isLoginFailed = false;
  roles: string[] = [];
  private loginInfo?: LoginInfo;

  constructor(private authService: AuthService,
              private tokenStorage: TokenStorageService,
              private _snackBar: MatSnackBar,
              private formBuilder: FormBuilder,
              private router: Router) {
  }

  ngOnInit() {
    if (this.tokenStorage.getToken() != null && this.tokenStorage.getToken() != '{}') {
      this.isLoggedIn = true;
      this.roles = this.tokenStorage.getAuthorities();
    }
    this.form = this.formBuilder.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(8)]],
    })
  }

  get f(): { [key: string]: AbstractControl } {
    return this.form.controls;
  }

  onSubmit() {
    if (this.form.invalid) {
      return;
    }

    this.loginInfo = new LoginInfo(this.form.value.email, this.form.value.password);

    this.authService.attemptAuth(this.loginInfo).subscribe(
      data => {
        this.tokenStorage.saveToken(data.token || '{}');
        this.tokenStorage.saveUsername(data.username || '{}');
        this.tokenStorage.saveAuthorities(data.authorities || []);

        this.isLoginFailed = false;
        this.isLoggedIn = true;
        this.token = this.tokenStorage.getToken();
        this.roles = this.tokenStorage.getAuthorities();
        this.router.navigate(['/home']).then(() => {
        });
      },
      error => {
        this._snackBar.open(error.error?.message || 'Oops! Error occurred', 'Dismiss');
        this.isLoginFailed = true;
      }
    );
  }

}
