import { Component, ElementRef, HostListener, Inject, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { NanoDialogBase } from 'src/app/shared/dialogs/nano-base-dialog';
import { NanoValidators } from 'src/app/shared/nano-validators';

@Component({
  selector: 'app-admin-password-dialog',
  templateUrl: './admin-password-dialog.component.html',
  styleUrls: ['./admin-password-dialog.component.scss']
})
export class AdminPasswordDialogComponent extends NanoDialogBase<AdminPasswordDialogComponent> implements OnInit {

  passwordForm = new FormGroup({
    password: new FormControl(''),
    oldPassword: new FormControl('')
  });

  currentMode: AdminPasswordMode;
  dialogModes = AdminPasswordMode;

  constructor(public dialogRef: MatDialogRef<AdminPasswordDialogComponent>, @Inject(MAT_DIALOG_DATA) public adminPasswordDialogData: AdminPasswordData) { 
    super(dialogRef);
    this.currentMode = adminPasswordDialogData.adminPasswordMode;
  }

  ngOnInit(): void {
    if(this.currentMode == AdminPasswordMode.CHANGE){
      this.passwordForm.get("password").addValidators([Validators.required]);
      this.passwordForm.get("oldPassword").addValidators([Validators.required]);
    }
    else if(this.currentMode == AdminPasswordMode.FIRST)
    {
      this.passwordForm.get("password").addValidators([Validators.required, NanoValidators.controlEquals(this.passwordForm.get("oldPassword"))]);
      this.passwordForm.get("oldPassword").addValidators([Validators.required]);

      this.passwordForm.get("password").valueChanges.subscribe(e => {
        if(this.passwordForm.get("oldPassword").touched){
          this.passwordForm.get("oldPassword").updateValueAndValidity();
        }
      });
    }
    else
    {
      this.passwordForm.get("password").addValidators([Validators.required]);
    }
  }

  public setPassword(){
    this.dialogRef.close({password: this.passwordForm.get("password").value, oldPassword: this.passwordForm.get("oldPassword").value});
  }
}

interface AdminPasswordData{
  adminPasswordMode: number
}

enum AdminPasswordMode{
  PROVIDE = 0,
  CHANGE = 1,
  FIRST = 2
}