import { Component, Inject, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IInstanceModel } from '@fleio-api/openstack/model/instance.model';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';

@Component({
  selector: 'app-instance-change-password-dialog',
  templateUrl: './instance-change-password-dialog.component.html',
  styleUrls: ['./instance-change-password-dialog.component.scss']
})
export class InstanceChangePasswordDialogComponent implements IBaseDialog {
  showPassword = false;
  backendErrors = {};
  loading = false;
  changePasswordForm = this.formBuilder.group({
    password: ['', Validators.required],
  });
  dialogTitle = $localize`Change admin password for instance ${this.data?.instance?.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Change password`,
      primary: true,
      callback: () => this.changePassword(),
    }),
  ];
  dialogForm = this.changePasswordForm;
  @ViewChild('formErrors') formErrors;
  fieldRequiredTxt = $localize`This field is required!`;
  holdButtonTxt = $localize`Hold button to reveal password`;

  constructor(
    public dialogRef: MatDialogRef<InstanceChangePasswordDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { instance: IInstanceModel },
    private instancesApiService: InstancesApiService,
    private formBuilder: UntypedFormBuilder,
  ) {
  }

  public changePassword() {
    if (!this.changePasswordForm.valid) {
      return;
    }
    this.loading = true;
    this.instancesApiService.changePassword(
      this.data.instance.id, this.changePasswordForm.controls.password.value,
    ).subscribe(() => {
      this.loading = false;
      this.dialogRef.close(true);
    }, error => {
      this.loading = false;
      this.backendErrors = error.error;
      this.formErrors.setBackendErrors(error.error);
    });
  }
}
