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 { User } from 'src/app/model/auth/user';
import { UsersColumns } from 'src/app/modules/admin/administration/users/users.columns';
import { UsersDataService } from 'src/app/modules/admin/administration/users/users.data.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.page.html',
  styleUrl: './users.page.scss',
})
export class UsersPage extends PageBase<User, UsersDataService, UsersColumns> {
  constructor(
    private toast: ToastService,
    private confirmation: ConfirmationDialogService
  ) {
    super(true, {
      read: [PermissionsEnum.users],
      create: [PermissionsEnum.usersCreate],
      update: [PermissionsEnum.usersUpdate],
      delete: [PermissionsEnum.usersDelete],
      restore: [PermissionsEnum.usersDelete],
    });
  }

  async onInit(): Promise<void> {}

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

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