import { Component, HostListener, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { SecurityService } from '../../logic/services/security.service';
import { FormHelper } from '../../ui/controls/form-helper';
import { Router } from '@angular/router';

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

  contextFormGroup;
  error = {
    exist: false,
    data: ''
  };

  @HostListener('window:keydown.enter', ['$event'])
  handleKeyDown(event: KeyboardEvent) {
    this.login();
  }

  constructor(private fb: FormBuilder,
              private securityService: SecurityService,
              private router: Router) {
    this.contextFormGroup = fb.group({
      username: ['', Validators.required],
      password: ['', Validators.required]
    });
  }

  isInvalid(cname: string) {
    return FormHelper.isInvalid(this.contextFormGroup, cname);
  }

  ngOnInit() {
    if (this.securityService.loggedIn()) {
      this.router.navigate(['/dashboard']).then();
    }
  }

  login() {

    if (!this.contextFormGroup.valid) {
      FormHelper.setFocusToInvalidControl(this.contextFormGroup);
      return;
    }

    this.securityService.loginByUsername(this.contextFormGroup.value)
      .subscribe(response => {
        this.error = {
          exist: false,
          data: ''
        };
        this.securityService.setAuth(response.accessToken);
        console.clear();
      }, err => {
        this.error = {
          exist: true,
          data: err.error.messages[0].message
        };
      });
  }
}
