import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IVolumeModel } from '@fleio-api/openstack/model/volume.model';
import { NotificationService } from '@shared/ui-api/notification.service';
import { VolumeSnapshotsApiService } from '@fleio-api/openstack/volume/volume-snapshots-api.service';
import { VolumesApiService } from '@fleio-api/openstack/volume/volumes-api.service';
import { IVolumeSnapshotModel } from '@fleio-api/openstack/model/volume-snapshot.model';
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-revert-volume-to-snapshot-dialog',
  templateUrl: './revert-volume-to-snapshot-dialog.component.html',
  styleUrls: ['./revert-volume-to-snapshot-dialog.component.scss']
})
export class RevertVolumeToSnapshotDialogComponent implements IBaseDialog, OnInit {
  loading = false;
  snapshot: IVolumeSnapshotModel;
  dialogTitle = $localize`Revert volume ${this.data?.volume?.name} to snapshot`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Revert volume`,
      primary: true,
      callback: () => this.revertToSnapshot(),
    }),
  ];

  constructor(
    public dialogRef: MatDialogRef<RevertVolumeToSnapshotDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      volume: IVolumeModel;
    },
    private volumesApiService: VolumesApiService,
    private volumeSnapshotsApiService: VolumeSnapshotsApiService,
    private notificationService: NotificationService,
  ) {
  }

  ngOnInit() {
    if (this.data.volume) {
      this.loading = true;
      this.volumeSnapshotsApiService.getSnapshotForRevert(this.data.volume.id).subscribe({
        next: snapshot => {
          this.snapshot = snapshot;
          if (!this.snapshot) {
            this.dialogActions[0].disabled = true;
          }
        },
        error: () => {
          this.dialogActions[0].disabled = true;
        }
      }).add(() => {
        this.loading = false;
      });
    }
  }

  revertToSnapshot() {
    if (!this.data.volume) {
      return;
    }

    this.loading = true;
    this.volumesApiService.revertToSnapshot(this.data.volume.id, this.snapshot.id).subscribe({
      next: result => {
        if (result) {
          this.dialogRef.close($localize`Ok`);
          this.notificationService.showMessage($localize`Revert to snapshot scheduled`);
        } else {
          this.dialogRef.close('');
        }
      }, error: error => {
        this.notificationService.showMessage(error.error.detail);
        this.dialogRef.close(false);
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
