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

@Component({
  selector: 'cre-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.sass']
})
export class EditComponent extends SubscribingComponent {
  materialType: MaterialType | null
  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'
        }
      ]
    }
  ]
  unknownError = false
  errorMessage: string | null

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

  ngOnInit() {
    super.ngOnInit()

    const id = parseInt(this.activatedRoute.snapshot.paramMap.get('id'))
    this.subscribe(
      this.materialTypeService.get(id),
      {
        next: materialType => this.materialType = materialType,
        error: err => {
          if (err.status === 404) {
            this.router.navigate(['/employee/list'])
          } else {
            this.unknownError = true
          }
        }
      },
      1
    )
  }

  submit(values) {
    this.subscribe(
      this.materialTypeService.update(this.materialType.id, values.name, values.prefix),
      {
        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)
        }
      }
    )
  }

  delete() {
    this.subscribe(
      this.materialTypeService.delete(this.materialType.id),
      {
        next: () => this.router.navigate(['/catalog/materialtype/list']),
        error: err => {
          this.unknownError = true
          console.log(err)
        }
      }
    )
  }
}
