import { Component, Inject, OnInit } 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 { NotificationService } from '@shared/ui-api/notification.service';
import { ConfigService } from '@shared/config/config.service';
import { HttpErrorResponse } from '@angular/common/http';
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 { RefreshService } from '@shared/ui-api/refresh.service';

@Component({
  selector: 'app-instance-delete-dialog',
  templateUrl: './instance-delete-dialog.component.html',
  styleUrls: ['./instance-delete-dialog.component.scss']
})
export class InstanceDeleteDialogComponent implements IBaseDialog, OnInit {
  loading = false;
  bootFromVolume = false;
  deleteBootVolume = false;
  importantMessage = '';
  dialogTitle = $localize`Delete instance ${this.data.instance.name || this.data.instance.id}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Delete`,
      primary: true,
      callback: () => this.delete(),
    }),
  ];

  constructor(
    private config: ConfigService,
    private notificationService: NotificationService,
    private instancesApiService: InstancesApiService,
    public dialogRef: MatDialogRef<InstanceDeleteDialogComponent>,
    private refreshService: RefreshService,
    @Inject(MAT_DIALOG_DATA) public data: {
      instance: IInstanceModel;
    },
  ) {
  }

  delete() {
    this.loading = true;
    this.refreshService.resetPageChanged();
    this.instancesApiService.delete(this.data.instance.id).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`Instance delete queued`);
        this.dialogRef.close(true);
        this.refreshService.redirect(this.config.getPanelUrl('openstack/instances'), [], true);
      },
      error: (error: HttpErrorResponse) => {
        let message = $localize`Failed to delete instance, check logs for details`;
        if (error.status === 403) {
          message = error?.error?.detail || message;
        }
        this.notificationService.showMessage(message);
        this.dialogRef.close(true);
      }
    }).add(() => {
      this.loading = false;
    });
  }

  setImportantMessage() {
    if (this.bootFromVolume) {
      if (this.deleteBootVolume) {
        this.importantMessage = $localize`Boot volume will also be deleted.`;
      } else {
        this.importantMessage = $localize`Boot volume will not be deleted, you will have to delete the volume manually.`;
      }
    }
  }

  ngOnInit(): void {
    this.loading = true;
    this.instancesApiService.getVolumeAttachments(this.data.instance.id).subscribe({
      next: response => {
        for (const volumeAttachment of response.objects) {
          if (volumeAttachment.is_boot) {
            this.bootFromVolume = true;
            this.deleteBootVolume = volumeAttachment.delete_on_termination;
            this.setImportantMessage();
            break;
          }
        }
      },
      error: () => {
        this.notificationService.showMessage(
          $localize`Could not load instance attached volumes info. Some information may not be shown.`
        );
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
