import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IDbaasInstanceModel } from '@fleio-api/openstack/model/dbaas-instance.model';
import { DbaasInstancesApiService } from '@fleio-api/openstack/dbaas/dbaas-instances-api.service';
import { AuthService } from '@shared/auth/auth.service';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
  selector: 'app-resize-database-instance-volume-dialog',
  templateUrl: './resize-database-instance-volume-dialog.component.html',
  styleUrls: ['./resize-database-instance-volume-dialog.component.scss']
})
export class ResizeDatabaseInstanceVolumeDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  volumeResizeForm = this.formBuilder.group({
    volume_size: ['', [Validators.required, Validators.max(50)]],
  });
  dialogTitle = $localize`Resize volume for ${this.data.database_instance.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Resize`,
      primary: true,
      callback: () => this.resize(),
    }),
  ];
  dialogForm = this.volumeResizeForm;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<ResizeDatabaseInstanceVolumeDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { database_instance: IDbaasInstanceModel },
    private dbaasInstancesApiService: DbaasInstancesApiService,
    private formBuilder: UntypedFormBuilder,
    public authService: AuthService,
    private notificationService: NotificationService,
  ) {
  }

  public resize() {
    if (this.volumeResizeForm.invalid) {
      return;
    }
    this.loading = true;
    this.dbaasInstancesApiService.resizeVolume(
      this.data.database_instance.id, this.volumeResizeForm.controls.volume_size.value,
    ).subscribe({
      next: () => {
        this.loading = false;
        this.notificationService.showMessage($localize`Volume resize queued.`);
        this.dialogRef.close(true);
      }, error: (error) => {
        this.formErrors.setBackendErrors(error.error);
        this.loading = false;
      }
    });
  }

  ngOnInit() {
  }

}
