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-totp.component.html',
  styleUrls: ['./login-totp.component.scss']
})
export class LoginTotpComponent implements OnInit {

  form: FormGroup;
  public loginInvalid: boolean;
  public apiUrl = environment.apiUrl;
  targetRoute = '/account/info';

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


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

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

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

      const totpModel = {
        code: this.form.get('code').value,
        keep: this.form.get('keep').value
      };

      this.authService.loginTotp(totpModel).subscribe((response: any) => {
        this.router.navigate([this.targetRoute]);
      }, error => {
        this.loginInvalid = true;
      });

    }
  }

}
