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 {
  CreateDatabaseUserDialogComponent
} from '@shared/common-dialogs/openstack/dbaas/create-database-user-dialog/create-database-user-dialog.component';
import { DbaasInstancesApiService } from '@fleio-api/openstack/dbaas/dbaas-instances-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import {
  GrantDatabasesAccessDialogComponent
} from '@shared/common-dialogs/openstack/dbaas/grant-databases-access-dialog/grant-databases-access-dialog.component';

@Component({
  selector: 'app-dbaas-instance-users-tab',
  templateUrl: './dbaas-instance-users-tab.component.html',
  styleUrls: ['./dbaas-instance-users-tab.component.scss']
})
export class DbaasInstanceUsersTabComponent extends DetailsComponentBase<IDbaasInstanceModel> {
  tableData: {
    name: string;
    databases: Array<string>;
  }[] = [];
  displayedColumns: string[] = ['name', 'databases', 'host', '(actions)'];
  loading = true;
  deleteUserTooltip = $localize`Delete user`;
  grantDatabasesAccessTooltip = $localize`Grant databases access`;
  revokeDatabaseAccessTooltip = $localize`Revoke database access`;

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

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

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

  createNewUser() {
    this.matDialog.open(
      CreateDatabaseUserDialogComponent, {
        data: {
          database_instance: this.object,
        },
        autoFocus: false,
      }
    ).afterClosed().subscribe(result => {
      if (result) {
        this.loadUsers();
      }
    });
  }

  grantDatabasesAccess(username: string, databases: Array<Record<string, string>>) {
    const alreadyExistingDbs = [];
    databases.forEach(database => {
      alreadyExistingDbs.push(database.name);
    });
    this.matDialog.open(
      GrantDatabasesAccessDialogComponent, {
        data: {
          username,
          database_instance: this.object,
          existing_dbs: alreadyExistingDbs,
        },
        autoFocus: false,
      }
    ).afterClosed().subscribe(result => {
      if (result) {
        this.loadUsers();
      }
    });
  }

  revokeDatabaseAccess(username: string, database) {
    this.notificationService.confirmDialog(
      {
        title: $localize`Revoke ${username}'s access to database ${database}`,
        message: $localize`Are you sure you want to revoke ${username}'s access to database ${database}?`,
        noButtonName: $localize`Cancel`,
        yesButtonName: $localize`Revoke access`,
      }
    ).subscribe(result => {
      if (result?.button === 'yes') {
        this.dbaasInstancesApiService.revokeDatabaseAccess(this.object.id, username, database).subscribe({
          next: (response) => {
            this.notificationService.showMessage(response.detail);
            this.loadUsers();
          }, error: () => {
            this.notificationService.showMessage($localize`Failed to revoke access for user`);
          }
        });
      }
    });
  }

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