import {Component} from '@angular/core';
import {Observable} from "rxjs";
import {GroupService} from "../../services/group.service";
import {EmployeeGroup, EmployeePermission} from "../../../shared/model/employee";
import {takeUntil} from "rxjs/operators";
import {animate, state, style, transition, trigger} from "@angular/animations";
import {AccountService} from "../../../accounts/services/account.service";
import {SubscribingComponent} from "../../../shared/components/subscribing.component";

@Component({
  selector: 'cre-groups',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.sass'],
  animations: [
    trigger('detailExpand', [
      state('collapsed', style({height: '0px', minHeight: '0'})),
      state('expanded', style({height: '*'})),
      transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)'))
    ])
  ]
})
export class ListComponent extends SubscribingComponent {
  groups$: Observable<EmployeeGroup[]>
  defaultGroup: EmployeeGroup = null
  columns = ['name', 'permissionCount', 'employeeCount', 'defaultGroup', 'editGroup']
  expandedElement: EmployeeGroup | null

  constructor(
    private groupService: GroupService,
    private accountService: AccountService
  ) {
    super()
  }

  ngOnInit(): void {
    this.groups$ = this.groupService.all.pipe(takeUntil(this.destroy$))
    this.subscribe(
      this.groupService.defaultGroup,
      {next: g => this.defaultGroup = g}
    )
  }

  setDefaultGroup(group: EmployeeGroup) {
    this.subscribe(
      this.groupService.setDefaultGroup(group),
      {next: () => this.defaultGroup = group}
    )
  }

  isDefaultGroup(group: EmployeeGroup): boolean {
    return this.defaultGroup && this.defaultGroup.id == group.id
  }

  get canViewEmployee(): boolean {
    return this.accountService.hasPermission(EmployeePermission.VIEW_EMPLOYEE)
  }

  get canEditGroup(): boolean {
    return this.accountService.hasPermission(EmployeePermission.EDIT_EMPLOYEE_GROUP)
  }

  get canSetBrowserDefaultGroup(): boolean {
    return this.accountService.hasPermission(EmployeePermission.SET_BROWSER_DEFAULT_GROUP)
  }
}
