import {Component} from '@angular/core';
import {FormField} from "../../../shared/components/entity-add/entity-add.component";
import {Validators} from "@angular/forms";
import {MaterialService} from "../../service/material.service";
import {MaterialTypeService} from "../../../material-type/service/material-type.service";
import {Router} from "@angular/router";
import {SubscribingComponent} from "../../../shared/components/subscribing.component";
import {map} from "rxjs/operators";

@Component({
  selector: 'cre-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.sass']
})
export class AddComponent extends SubscribingComponent {
  formFields: FormField[] = [
    {
      name: 'name',
      label: 'Code',
      icon: 'form-textbox',
      type: 'text',
      validator: Validators.required,
      errorMessages: [
        {conditionFn: (errors) => errors.required, message: 'Un code est requis'}
      ]
    },
    {
      name: 'inventoryQuantity',
      label: 'Quantité en inventaire',
      icon: 'beaker-outline',
      type: 'number',
      validator: Validators.compose([Validators.required, Validators.min(0)]),
      errorMessages: [
        {conditionFn: errors => errors.required, message: 'Une quantité en inventaire est requise'},
        {conditionFn: errors => errors.min, message: 'La quantité doit être supérieure ou égale à 0'}
      ],
      step: '0.01'
    },
    {
      name: 'materialType',
      label: 'Type de produit',
      icon: 'shape-outline',
      type: 'select',
      validator: Validators.required,
      errorMessages: [
        {conditionFn: errors => errors.required, message: 'Un type de produit est requis'}
      ],
      options$: this.materialTypeService.all.pipe(map(types => types.map(t => {
        return {value: t.id, label: t.name}
      })))
    },
    {
      name: 'simdutFile',
      label: 'Fiche signalitique',
      icon: 'file-outline',
      type: 'file',
      fileType: 'application/pdf'
    }
  ]
  unknownError = false
  errorMessage: string | null

  constructor(
    private materialService: MaterialService,
    private materialTypeService: MaterialTypeService,
    private router: Router
  ) {
    super()
  }

  submit(values) {
    this.subscribe(
      this.materialService.save(values.name, values.inventoryQuantity, values.materialType, values.simdutFile),
      {
        next: () => this.router.navigate(['/catalog/material/list']),
        error: err => {
          if (err.status == 409) {
            this.errorMessage = `Un produit avec le nom '${values.name}' existe déjà`
          } else {
            this.unknownError = true
          }
          console.log(err)
        }
      }
    )
  }
}
