import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../Services/auth.service';
import { TokenStorageService } from '../../Services/token.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
  form: any = {
    email: null,
    password: null,
  };

  isLoggedIn = false;
  isLoginFailed = false;
  errorMessage = '';
  accountName = '';

  /**
   * @param  {AuthService} privateauthService
   * @param  {TokenStorageService} privatetokenStorage
   * @param  {Router} privaterouter
   */
  constructor(
    private authService: AuthService,
    private tokenStorage: TokenStorageService,
    private router: Router
  ) {}

  //ngOnInit() checks if a user is logged in
  ngOnInit(): void {
    this.tokenStorage.signOut();
    if (this.tokenStorage.getToken()) {
      this.isLoggedIn = true;
    }
  }

  //onSubmit() saves valuable information in session storage
  onSubmit(): void {
    const { email, password } = this.form;
    this.authService.login(email, password).subscribe(
      (data) => {
        this.tokenStorage.saveToken(data.data.token);
        this.tokenStorage.saveUser(data.data);

        this.isLoginFailed = false;
        this.isLoggedIn = true;
        this.accountName = email;
        this.router.navigate(['']);
      },
      (err) => {
        this.errorMessage = err.error.message;
        this.isLoginFailed = true;
      }
    );
  }

  //reloadPage() reloads the page
  reloadPage(): void {
    window.location.reload();
  }
}
