import {Component, Input} from '@angular/core';
import {Observable} from "rxjs";
import {SubscribingComponent} from "../subscribing.component";
import {AccountService} from "../../../accounts/services/account.service";
import {EmployeePermission} from "../../model/employee";

@Component({
  selector: 'cre-entity-list',
  templateUrl: './entity-list.component.html',
  styleUrls: ['./entity-list.component.sass']
})
export class EntityListComponent<T> extends SubscribingComponent {
  @Input() entities$: Observable<T>
  @Input() columns: TableColumn[]
  @Input() icons: TableIcon[]
  @Input() buttons?: TableButton[]
  @Input() addLink: string

  constructor(
    private accountService: AccountService
  ) {
    super()
  }

  hasPermissionToUseButton(button: TableButton): boolean {
    return !button.permission || this.accountService.hasPermission(button.permission)
  }

  openExternalLink(button: TableButton, entity: T) {
    let externalLink = null
    // @ts-ignore
    if (button.link && button.link.externalLink) {
      // @ts-ignore
      externalLink = button.link.externalLink
    } else {
      const linkFnResult = button.linkFn(entity)
      // @ts-ignore
      if (linkFnResult && linkFnResult.externalLink) {
        // @ts-ignore
        externalLink = linkFnResult.externalLink
      }
    }

    if (externalLink) window.open(externalLink, "_blank")
  }

  get tableCols(): string[] {
    const cols = this.columns.map(c => c.def)
    if (this.icons) {
      this.icons.forEach((_, i) => cols.push(`icon${i}`))
    }
    if (this.buttons) {
      this.buttons.forEach((_, i) => cols.push(`button${i}`))
    }
    return cols
  }
}

export class TableColumn {
  constructor(
    public def: string,
    public title: string,
    public valueFn: (T) => string
  ) {
  }
}

export class TableIcon {
  constructor(
    public icon: string,
    public color: string,
    public title: string,
    public disabledFn: (T) => boolean
  ) {
  }
}

export class TableButton {
  constructor(
    public text: string,
    public link: string | { externalLink: string } | null,
    public linkFn: (T) => string | { externalLink: string } | null,
    public permission: EmployeePermission | null,
    public disabledFn: (T) => boolean | null
  ) {
  }
}
