import {Component} from '@angular/core';
import {CompanyService} from "../../service/company.service";
import {Validators} from "@angular/forms";
import {SubscribingComponent} from "../../../shared/components/subscribing.component";
import {FormField} from "../../../shared/components/entity-add/entity-add.component";
import {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'}
      ]
    }
  ]
  unknownError = false
  errorMessage: string | null

  constructor(
    private companyService: CompanyService,
    private router: Router
  ) {
    super()
  }

  submit(values) {
    this.subscribe(
      this.companyService.save(values.name),
      {
        next: () => this.router.navigate(['/catalog/company/list']),
        error: err => {
          if (err.status == 409) {
            this.errorMessage = `Une bannière avec le nom '${values.name}' existe déjà`
          } else {
            this.unknownError = true
          }
          console.log(err)
        }
      }
    )
  }
}
