import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthService } from './../../services/auth.service';
import { Router, ActivatedRoute } from '@angular/router';

import { environment } from './../../../environments/environment';

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

  form: FormGroup;
  public loginInvalid: boolean;
  public apiUrl = environment.apiUrl;
  targetRoute = '/services';
  loginModel = {};

  constructor(private formBuilder: FormBuilder, private authService: AuthService, private router: Router, private route: ActivatedRoute) { }

  async ngOnInit() {
    this.form = this.formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.required],
      keep: ['']
    });

    this.route.queryParams.subscribe(params => {
      if (params['target']) {
        this.targetRoute = params['target'];
      }
    });
  }

  async login() {
    this.loginInvalid = false;
    if (this.form.valid) {

      const loginModel = {
        username: this.form.get('username').value,
        password: this.form.get('password').value,
        keep: this.form.get('keep').value
      };

      this.authService.login(loginModel).subscribe((response: any) => {
        this.router.navigate([this.targetRoute]);
      }, error => {
        if (error.status == 428) {
          this.router.navigate(["/login/totp"], { queryParams: { target: this.targetRoute } });
        } else {
          this.loginInvalid = true;
        }
      });

    }
  }

}
