import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IVolumeModel } from '@fleio-api/openstack/model/volume.model';
import { VolumesApiService } from '@fleio-api/openstack/volume/volumes-api.service';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';

@Component({
  selector: 'app-volume-rename',
  templateUrl: './volume-rename.component.html',
  styleUrls: ['./volume-rename.component.scss']
})
export class VolumeRenameComponent implements OnInit {
  renameForm = this.formBuilder.group({
    name: ['', Validators.required],
  });
  @ViewChild('formErrors') formErrors;
  dialogTitle = $localize`Rename volume ${this.data.volume.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Rename`,
      primary: true,
      callback: () => this.renameVolume(),
    }),
  ];
  dialogForm = this.renameForm;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<VolumeRenameComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { volume: IVolumeModel },
    private volumesApiService: VolumesApiService,
    private formBuilder: UntypedFormBuilder,
    private refreshService: RefreshService,
  ) {
  }

  ngOnInit() {
    this.renameForm.controls.name.setValue(this.data.volume.name);
  }

  renameVolume() {
    this.loading = true;
    this.volumesApiService.rename(this.data.volume.id, this.renameForm.value).subscribe({
      next: result => {
        if (result) {
          this.dialogRef.close($localize`Volume renamed`);
          this.refreshService.refresh();
        } else {
          this.dialogRef.close('');
        }
      },
      error: error => {
        this.formErrors.setBackendErrors(error.error);
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
