import { Component } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IDbaasInstanceModel } from '@fleio-api/openstack/model/dbaas-instance.model';
import { ConfigService } from '@shared/config/config.service';
import { MatDialog } from '@angular/material/dialog';
import { DbaasInstancesApiService } from '@fleio-api/openstack/dbaas/dbaas-instances-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import {
  CreateDatabaseDialogComponent
} from '@shared/common-dialogs/openstack/dbaas/create-database-dialog/create-database-dialog.component';

@Component({
  selector: 'app-dbaas-instance-databases-tab',
  templateUrl: './dbaas-instance-databases-tab.component.html',
  styleUrls: ['./dbaas-instance-databases-tab.component.scss']
})
export class DbaasInstanceDatabasesTabComponent extends DetailsComponentBase<IDbaasInstanceModel> {
  tableData: {
    name: string;
  }[] = [];
  displayedColumns: string[] = ['name', '(actions)'];
  loading = true;
  deleteDatabaseTooltip = $localize`Delete database`;

  constructor(
    public config: ConfigService,
    private matDialog: MatDialog,
    private dbaasInstancesApiService: DbaasInstancesApiService,
    private notificationService: NotificationService,
  ) {
    super();
  }

  loadDatabases() {
    this.loading = true;
    this.dbaasInstancesApiService.getDatabases(this.object.id).subscribe({
      next: value => {
        this.tableData = value.databases;
        this.loading = false;
      }, error: error => {
        if (error.error?.detail) {
          this.notificationService.showMessage(error.error.detail);
        }
        this.loading = false;
      }
    });
  }

  protected tabActivated() {
    super.tabActivated();
    this.loadDatabases();
  }

  createNewDatabase() {
    this.matDialog.open(
      CreateDatabaseDialogComponent, {
        data: {
          database_instance: this.object,
        },
        autoFocus: false,
      }
    ).afterClosed().subscribe(result => {
      if (result) {
        this.loadDatabases();
      }
    });
  }

  deleteDatabase(name: string) {
    this.notificationService.confirmDialog(
      {
        title: $localize`Delete database ${name}`,
        message: $localize`Are you sure you want to delete database ${name}?`,
        noButtonName: $localize`Cancel`,
        yesButtonName: $localize`Delete`,
      }
    ).subscribe(result => {
      if (result?.button === 'yes') {
        this.dbaasInstancesApiService.deleteDatabase(this.object.id, name).subscribe({
          next: (response) => {
            this.notificationService.showMessage(response.detail);
            this.loadDatabases();
          }, error: () => {
            this.notificationService.showMessage($localize`Failed to delete database`);
          }
        });
      }
    });
  }
}
