import {Component} from '@angular/core';
import {SubscribingComponent} from "../../../shared/components/subscribing.component";
import {MaterialService} from "../../service/material.service";
import {EmployeePermission} from "../../../shared/model/employee";
import {environment} from "../../../../../environments/environment";

@Component({
  selector: 'cre-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.sass']
})
export class ListComponent extends SubscribingComponent {
  materials$ = this.materialService.all
  columns = [
    {def: 'name', title: 'Code', valueFn: t => t.name},
    {def: 'inventoryQuantity', title: 'Quantité', valueFn: t => t.inventoryQuantity},
    {def: 'materialType', title: 'Type de produit', valueFn: t => t.materialType.name}
  ]
  icons = [{
    icon: 'text-box-remove',
    color: 'warn',
    title: 'Ce produit n\'a pas de fiche signalitique',
    disabledFn: t => this.hasSimdutMap[t.id]
  }]
  buttons = [{
    text: 'Modifier',
    linkFn: t => `/catalog/material/edit/${t.id}`,
    permission: EmployeePermission.EDIT_MATERIAL
  }, {
    text: 'Fiche signalitique',
    linkFn: t => {
      return {
        externalLink: environment.apiUrl + `/material/${t.id}/simdut`
      }
    },
    disabledFn: t => !this.hasSimdutMap[t.id]
  }]

  private hasSimdutMap: any = {}

  constructor(
    private materialService: MaterialService
  ) {
    super()
  }

  ngOnInit() {
    super.ngOnInit();

    this.subscribe(
      this.materials$,
      {
        next: mArray => {
          mArray.forEach(m => {
            this.subscribe(
              this.materialService.hasSimdut(m.id),
              { next: b => this.hasSimdutMap[m.id] = b }
            )
          })
        }
      },
      1
    )
  }
}
