import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { IVolumeModel } from '@fleio-api/openstack/model/volume.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-instance-details-create-snapshot-dialog',
  templateUrl: './instance-details-attach-volume-dialog.component.html',
  styleUrls: ['./instance-details-attach-volume-dialog.component.scss']
})
export class InstanceDetailsAttachVolumeDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  loading = false;
  volumesToAttach: IVolumeModel[];
  attachVolumeForm: UntypedFormGroup = new UntypedFormGroup({
    volume_id: new UntypedFormControl('', Validators.required),
  });
  dialogTitle = $localize`Attach a volume to instance ${this.data.instanceName || this.data.instanceId}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Attach`,
      primary: true,
      callback: () => this.attachVolume(),
    }),
  ];
  dialogForm = this.attachVolumeForm;

  constructor(
    private notificationService: NotificationService,
    private instancesApiService: InstancesApiService,
    public dialogRef: MatDialogRef<InstanceDetailsAttachVolumeDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      instanceId: string;
      instanceName: string;
      project: string;
      region: string;
    },
  ) {
  }

  ngOnInit() {
    this.volumesToAttach = [];
    this.loading = true;
    this.instancesApiService.getAttachableVolumes(
      this.data.instanceId,
      1000
    ).subscribe((response: FleioObjectsList<IVolumeModel>) => {
      this.volumesToAttach = response.objects;
      this.loading = false;
    });
  }

  attachVolume() {
    this.loading = true;
    const value = this.attachVolumeForm.value;
    if (!value.volume_id) {
      this.loading = false;
      return;
    }
    this.instancesApiService.attachVolume(this.data.instanceId, value).pipe().subscribe(() => {
      this.loading = false;
      this.dialogRef.close(true);
    }, error => {
      this.loading = false;
      this.notificationService.showMessage($localize`Failed to attach volume`);
      this.formErrors.setBackendErrors(error.error);
    });
  }

}
