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 { NotificationService } from '@shared/ui-api/notification.service';

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

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

  public rename() {
    if (this.databaseInstanceRenameForm.invalid) {
      return;
    }
    this.loading = true;
    this.dbaasInstancesApiService.rename(
      this.data.database_instance.id, this.databaseInstanceRenameForm.controls.name.value,
    ).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`Database instance was renamed successfully.`)
        this.dialogRef.close(true);
      }, error: (error) => {
        this.formErrors.setBackendErrors(error.error);
      }
    }).add(() => {
      this.loading = false;
    });
  }

  ngOnInit() {
    this.databaseInstanceRenameForm.controls.name.setValue(this.data.database_instance.name);
  }

}
