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

@Component({
  selector: 'cre-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.sass']
})
export class AddComponent extends SubscribingComponent {
  formFields: FormField[] = [
    {
      name: 'name',
      label: 'Nom',
      icon: 'form-textbox',
      type: 'text',
      validator: Validators.required,
      errorMessages: [
        {conditionFn: (errors) => errors.required, message: 'Un nom est requis'},
      ]
    },
    {
      name: 'prefix',
      label: 'Préfixe',
      icon: 'label-variant',
      type: 'text',
      validator: Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(3)]),
      errorMessages: [
        {conditionFn: (errors) => errors.required, message: 'Un préfixe est requis'},
        {
          conditionFn: (errors) => errors.minlength || errors.maxlength,
          message: 'Le préfixe doit faire exactement 3 caractères'
        }
      ]
    },
    {
      name: 'usePercentages',
      label: 'Utiliser les pourcentages',
      icon: 'percent',
      type: 'checkbox'
    }
  ]
  unknownError = false
  errorMessage: string | null

  constructor(
    private materialTypeService: MaterialTypeService,
    router: Router,
    activatedRoute: ActivatedRoute
  ) {
    super(activatedRoute, router)
  }

  submit(values) {
    this.subscribe(
      this.materialTypeService.save(values.name, values.prefix, values.usePercentages),
      {
        next: () => this.router.navigate(['/catalog/materialtype/list']),
        error: err => {
          if (err.status == 409 && err.error.id === values.name) {
            this.errorMessage = `Un type de produit avec le nom '${values.name}' existe déjà`
          } else if (err.status == 409 && err.error.id === values.prefix) {
            this.errorMessage = `Un type de produit avec le préfixe '${values.prefix}' exists déjà`
          } else {
            this.unknownError = true
          }
          console.log(err)
        }
      }
    )
  }
}
