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

@Component({
  selector: 'app-reset-volume-snapshot-state-dialog',
  templateUrl: './reset-volume-snapshot-state-dialog.component.html',
  styleUrls: ['./reset-volume-snapshot-state-dialog.component.scss']
})
export class ResetVolumeSnapshotStateDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') protected formErrors;
  backendErrors = {};
  snapshotForm = this.formBuilder.group({
    status: ['', Validators.required],
  });
  dialogTitle = $localize`Update volume snapshot`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Update snapshot`,
      primary: true,
      callback: () => this.createOrUpdate(),
    }),
  ];
  dialogForm = this.snapshotForm;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<ResetVolumeSnapshotStateDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      snapshot: IVolumeSnapshotModel;
    },
    private volumeSnapshotsApiService: VolumeSnapshotsApiService,
    private formBuilder: UntypedFormBuilder,
  ) {
  }

  ngOnInit() {
    if (this.data.snapshot) {
      this.snapshotForm.patchValue(this.data.snapshot);
    }
  }

  createOrUpdate() {
    const value = this.snapshotForm.value;

    this.loading = true;
    this.volumeSnapshotsApiService.resetState(this.data.snapshot.id, value.status).subscribe(result => {
      if (result) {
        this.dialogRef.close($localize`Snapshot state updated`);
      } else {
        this.dialogRef.close('');
      }
    }, error => {
      this.backendErrors = error.error;
      this.formErrors.setBackendErrors(error.error);
    }).add(() => {
      this.loading = false;
    });
  }
}
