import { Component } from '@angular/core';
import { PageBase } from 'src/app/core/base/page-base';
import { ToastService } from 'src/app/service/toast.service';
import { ConfirmationDialogService } from 'src/app/service/confirmation-dialog.service';
import { PermissionsEnum } from 'src/app/model/auth/permissionsEnum';
import { ApiKey } from 'src/app/model/entities/api-key';
import { ApiKeysDataService } from 'src/app/modules/admin/administration/api-keys/api-keys.data.service';
import { ApiKeysColumns } from 'src/app/modules/admin/administration/api-keys/api-keys.columns';

@Component({
  selector: 'app-api-keys',
  templateUrl: './api-keys.page.html',
  styleUrl: './api-keys.page.scss',
})
export class ApiKeysPage extends PageBase<
  ApiKey,
  ApiKeysDataService,
  ApiKeysColumns
> {
  constructor(
    private toast: ToastService,
    private confirmation: ConfirmationDialogService
  ) {
    super(true, {
      read: [PermissionsEnum.apiKeys],
      create: [PermissionsEnum.apiKeysCreate],
      update: [PermissionsEnum.apiKeysUpdate],
      delete: [PermissionsEnum.apiKeysDelete],
      restore: [PermissionsEnum.apiKeysDelete],
    });
  }

  load(silent?: boolean): void {
    if (silent) this.loading = true;
    this.dataService
      .load(this.filter, this.sort, this.skip, this.take)
      .subscribe(result => {
        this.result = result;
        this.loading = false;
      });
  }

  delete(apiKey: ApiKey): void {
    this.confirmation.confirmDialog({
      header: 'dialog.delete.header',
      message: 'dialog.delete.message',
      accept: () => {
        this.loading = true;
        this.dataService.delete(apiKey).subscribe(() => {
          this.toast.success('action.deleted');
          this.load();
        });
      },
      messageParams: { entity: apiKey.identifier },
    });
  }

  restore(apiKey: ApiKey): void {
    this.confirmation.confirmDialog({
      header: 'dialog.restore.header',
      message: 'dialog.restore.message',
      accept: () => {
        this.loading = true;
        this.dataService.restore(apiKey).subscribe(() => {
          this.toast.success('action.restored');
          this.load();
        });
      },
      messageParams: { entity: apiKey.identifier },
    });
  }
}
