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 { Group } from 'src/app/model/entities/group';
import { GroupsDataService } from 'src/app/modules/admin/groups/groups.data.service';
import { GroupsColumns } from 'src/app/modules/admin/groups/groups.columns';
import { takeUntil } from 'rxjs/operators';
import { SidebarService } from 'src/app/service/sidebar.service';

@Component({
  selector: 'app-groups',
  templateUrl: './groups.page.html',
  styleUrl: './groups.page.scss',
})
export class GroupsPage extends PageBase<
  Group,
  GroupsDataService,
  GroupsColumns
> {
  constructor(
    private toast: ToastService,
    private confirmation: ConfirmationDialogService,
    private sidebar: SidebarService
  ) {
    super(true, {
      read: [],
      create: [],
      update: [],
      delete: [],
      restore: [],
    });

    this.sidebar.selectedUserSpace$
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe(() => {
        this.load(true);
      });
  }

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

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