import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { AuthService } from './../../services/auth.service';
import { Router } from '@angular/router';

var openpgp = require('openpgp');
@Component({
  selector: 'app-password',
  templateUrl: './password.component.html',
  styleUrls: ['./password.component.scss']
})
export class PasswordComponent implements OnInit {

  model: any = {};
  public working: boolean;
  form: FormGroup;

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

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

  async passwordRequest() {
    this.working = true;
    const { keys: [privateKey] } = await openpgp.key.readArmored(this.model.privateKey);

    const model = {
      username: this.model.username
    }

    this.authService.passwordRequest(this.model.username).subscribe(async response => {

      if (privateKey) {
        const message = await openpgp.message.readArmored(response);

        const decrypted = await openpgp.decrypt({
          message: message,
          privateKeys: [privateKey]
        });
        this.working = false;
        this.router.navigate(['/password-reset'], { queryParams: { token: decrypted.data.trim() } });
      } else {
        this.working = false;
      }
    })

  }

}
