import { Component } from '@angular/core';
import { PageBase } from 'src/app/core/base/page-base';
import { Role } from 'src/app/model/entities/role';
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 { RolesColumns } from 'src/app/modules/admin/administration/roles/roles.columns';
import { RolesDataService } from 'src/app/modules/admin/administration/roles/roles.data.service';

@Component({
  selector: 'app-roles',
  templateUrl: './roles.page.html',
  styleUrl: './roles.page.scss',
})
export class RolesPage extends PageBase<Role, RolesDataService, RolesColumns> {
  constructor(
    private toast: ToastService,
    private confirmation: ConfirmationDialogService
  ) {
    super(true, {
      read: [PermissionsEnum.roles],
      create: [PermissionsEnum.rolesCreate],
      update: [PermissionsEnum.rolesUpdate],
      delete: [PermissionsEnum.rolesDelete],
      restore: [PermissionsEnum.rolesDelete],
    });
  }

  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(role: Role): void {
    this.confirmation.confirmDialog({
      header: 'dialog.delete.header',
      message: 'dialog.delete.message',
      accept: () => {
        this.loading = true;
        this.dataService.delete(role).subscribe(() => {
          this.toast.success('action.deleted');
          this.load();
        });
      },
      messageParams: { entity: role.name },
    });
  }

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