import { Component, OnInit, ViewChild, Inject } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators, NgForm } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';

import { AuthService } from './../../../services/auth.service';
import { UserService } from './../../../services/user.service';
import { MatchingValidator } from './../../../utils/matching.validator';

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


  model: any = {};
  public working: boolean;
  public success: boolean;
  public totp: boolean = false;

  passwordForm: FormGroup;
  @ViewChild('passwordFormDirective') private passwordFormDirective: NgForm;

  constructor(
    private formBuilder: FormBuilder,
    private userService: UserService,
    private authService: AuthService,
    public dialog: MatDialog) { }

  ngOnInit(): void {
    this.passwordForm = this.formBuilder.group({
      oldPassword: ['', Validators.required],
      password: ['', Validators.required],
      password2: ['', Validators.required]
    }, {
      validator: MatchingValidator('password', 'password2')
    });

    this.authService.isTotpEnabled().subscribe(response => {
      this.totp = true;
    }, error => {
      this.totp = false;
    })
  }

  changePassword() {
    if (this.passwordForm.valid && !this.working) {
      this.working = true;

      this.userService.password(this.model).subscribe((result: any) => {
        this.passwordFormDirective.resetForm();
        this.success = true;
        this.working = false;
      }, (error) => {
        this.working = false;
        if (error.status == 409) {
          let errors = {};
          for (let code of error.error) {
            errors[code.field] = errors[code.field] || {};
            errors[code.field][code.code] = true;
          }

          for (let code in errors) {
            this.passwordForm.get(code).setErrors(errors[code]);
          }
        }
      })
    }
  }

  createTotp() {
    this.authService.createTotp().subscribe((result: any) => {
      const dialogRef = this.dialog.open(SecurityTotpDialog, {
        closeOnNavigation: false,
        disableClose: true,
        data: result
      });

      dialogRef.afterClosed().subscribe(result => {
        if (result) {
          this.authService.enableTotp(result).subscribe((result: any) => {
            this.totp = true;
          })
        } else {
          this.authService.removeTotp().subscribe((result: any) => {
            this.totp = false;
          })
        }
      });
    })
  }


  enableTotp() {
    const dialogRef = this.dialog.open(SecurityTotpDialog, {
      closeOnNavigation: false,
      disableClose: true,
      data: {}
    });
  }

  removeTotp() {
    this.authService.removeTotp().subscribe((result: any) => {
      this.totp = false;
    })
  }

}


@Component({
  selector: 'app-security-totp-dialog',
  templateUrl: 'security-totp.dialog.html',
  styleUrls: ['./security.component.scss']
})
export class SecurityTotpDialog {

  code: FormControl;

  constructor(
    public dialogRef: MatDialogRef<SecurityTotpDialog>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) { }

  ngOnInit(): void {
    this.code = new FormControl('', [Validators.required, Validators.pattern("[0-9]{6}")]);
  }
}