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 { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-volume-extend',
  templateUrl: './volume-extend.component.html',
  styleUrls: ['./volume-extend.component.scss']
})
export class VolumeExtendComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') protected formErrors;
  backendErrors = {};
  extendForm = this.formBuilder.group({
    size: ['', ValidatorsHelper.requiredNumericValueValidator],
  });
  dialogTitle = $localize`Extend volume ${this.data.volume.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Extend`,
      primary: true,
      callback: () => this.extendVolume(),
    }),
  ];
  dialogForm = this.extendForm;
  loading = false;
  fieldRequiredText = $localize`This field is required`;

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

  ngOnInit() {
    this.extendForm.controls.size.setValue(this.data.volume.size);
  }

  extendVolume() {
    this.loading = true;
    this.volumesApiService.extend(this.data.volume.id, this.extendForm.value).subscribe(result => {
      if (result) {
        this.dialogRef.close($localize`Volume extend scheduled`);
        this.refreshService.refresh();
      } else {
        this.dialogRef.close('');
      }
    }, error => {
      this.backendErrors = error.error;
      this.formErrors.setBackendErrors(error.error);
    }).add(() => {
      this.loading = false;
    });
  }
}
