import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {AccountService} from "../../services/account.service";
import {Router} from "@angular/router";

@Component({
  selector: 'cre-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.sass']
})
export class LoginComponent implements OnInit {
  form: FormGroup
  idFormControl: FormControl
  passwordFormControl: FormControl

  invalidCredentials = false

  constructor(
    private formBuilder: FormBuilder,
    private accountService: AccountService,
    private router: Router
  ) {
  }

  ngOnInit(): void {
    if (this.accountService.isLoggedIn()) {
      this.router.navigate(['/'])
    }

    this.idFormControl = this.formBuilder.control(null, Validators.compose([Validators.required, Validators.pattern(new RegExp('^[0-9]+$'))]))
    this.passwordFormControl = this.formBuilder.control(null, Validators.required)
    this.form = this.formBuilder.group({
      id: this.idFormControl,
      password: this.passwordFormControl
    })
  }

  submit() {
    this.accountService.login(
      this.idFormControl.value,
      this.passwordFormControl.value,
      () => this.router.navigate(["/color"]),
      err => this.invalidCredentials = err.status === 401
    )
  }
}
