import { ChangeDetectorRef, Component, NgZone, OnInit } 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 {
  AddDatabaseBackupDialogComponent
} from '@shared/common-dialogs/openstack/dbaas/add-database-backup-dialog/add-database-backup-dialog.component';
import {
  CreateDatabaseFromBackupComponent
} from '@shared/common-dialogs/openstack/dbaas/create-database-from-backup/create-database-from-backup.component';
import { Router } from '@angular/router';

@Component({
  selector: 'app-dbaas-instance-backups-tab',
  templateUrl: './dbaas-instance-backups-tab.component.html',
  styleUrls: ['./dbaas-instance-backups-tab.component.scss']
})
export class DbaasInstanceBackupsTabComponent extends DetailsComponentBase<IDbaasInstanceModel> {
  tableData: {
    name: string;
    databases: Array<string>;
  }[] = [];
  displayedColumns: string[] = ['created', 'name', 'status', 'size', '(actions)'];
  loading = true;
  backupsRefreshing = false;

  constructor(
    public config: ConfigService,
    private matDialog: MatDialog,
    private router: Router,
    private dbaasInstancesApiService: DbaasInstancesApiService,
    private notificationService: NotificationService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
  }

  loadBackups(refresh=false) {
    if (!this.backupsRefreshing) {
      if (!refresh) {
        // do not show loading when refreshing, only on tab activate
        this.loading = true;
      }
      this.backupsRefreshing = true;
      this.dbaasInstancesApiService.getBackups(this.object.id).subscribe({
        next: value => {
          this.tableData = value.backups;
          this.loading = false;
        }, error: error => {
          if (error.error?.detail) {
            this.notificationService.showMessage(error.error.detail);
          }
          this.loading = false;
        }
      }).add(() => {
        this.backupsRefreshing = false;
      });
    }
  }

  protected refreshData() {
    super.refreshData();
    this.loadBackups(true);
  }

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

  createNewBackup() {
    this.matDialog.open(
      AddDatabaseBackupDialogComponent, {
        data: {
          database_instance: this.object,
        },
        autoFocus: false,
      }
    ).afterClosed().subscribe(result => {
      if (result) {
        this.loadBackups();
      }
    });
  }

  createInstanceFromBackup(backup) {
    this.matDialog.open(
      CreateDatabaseFromBackupComponent, {
        data: {
          database_instance: this.object,
          backup: backup,
        },
        autoFocus: false,
      }
    ).afterClosed().subscribe(result => {
      if (result) {
        this.router.navigateByUrl(this.config.getPanelUrl(`openstack/database-instances`));
      }
    });
  }

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