import {Component} from '@angular/core';
import {SubscribingComponent} from "../../../shared/components/subscribing.component";
import {RecipeService} from "../../services/recipe.service";
import {FormField} from "../../../shared/components/entity-add/entity-add.component";
import {FormBuilder, Validators} from "@angular/forms";
import {CompanyService} from "../../../company/service/company.service";
import {map} from "rxjs/operators";
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: 'description',
      label: 'Description',
      icon: 'text',
      type: 'text',
      validator: Validators.required,
      errorMessages: [
        {conditionFn: errors => errors.required, message: 'Une description est requise'}
      ]
    },
    {
      name: 'sample',
      label: 'Échantillon',
      icon: 'pound',
      type: 'number',
      validator: Validators.compose([Validators.required, Validators.min(0)]),
      errorMessages: [
        {conditionFn: errors => errors.required, message: 'Un numéro d\'échantillon est requis'},
        {conditionFn: errors => errors.min, message: 'Le numéro d\'échantillon doit être supérieur ou égal à 0'}
      ]
    },
    {
      name: 'approbationDate',
      label: 'Date d\'approbation',
      icon: 'calendar',
      type: 'date'
    },
    {
      name: 'remark',
      label: 'Remarque',
      icon: 'text',
      type: 'text'
    },
    {
      name: 'company',
      label: 'Bannière',
      icon: 'domain',
      type: 'select',
      validator: Validators.required,
      errorMessages: [
        {conditionFn: errors => errors.required, message: 'Une bannière est requise'}
      ],
      options$: this.companyService.all.pipe(map(companies => companies.map(c => {
        return {value: c.id, label: c.name}
      })))
    }
  ]
  unknownError = false
  errorMessage: string | null

  constructor(
    private recipeService: RecipeService,
    private companyService: CompanyService,
    router: Router,
    activatedRoute: ActivatedRoute
  ) {
    super(activatedRoute, router)
  }

  submit(values) {
    this.subscribe(
      this.recipeService.save(values.name, values.description, values.sample, values.approbationDate, values.remark, values.company),
      {
        next: recipe => this.urlUtils.navigateTo(`/color/edit/${recipe.id}`),
        error: err => {
          this.unknownError = true
          console.error(err)
        }
      }
    )
  }
}
