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

@Component({
  selector: 'cre-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.sass']
})
export class EditComponent extends SubscribingComponent {
  @ViewChild('simdutTemplate', {static: true}) simdutTemplateRef
  @ViewChild('simdutFileInput') simdutFileInput

  material: Material | null
  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'}
      ],
      valueFn: material => material.materialType.id,
      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
  hasSimdut = false

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

  ngOnInit() {
    super.ngOnInit();

    this.formFields[3].template = this.simdutTemplateRef

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

    this.subscribe(
      this.materialService.hasSimdut(id),
      {next: b => this.hasSimdut = b}
    )
  }

  submit(values) {
    this.subscribe(
      this.materialService.update(this.material.id, 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)
        }
      }
    )
  }

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

  openSimdutUrl() {
    const simdutUrl = environment.apiUrl + `/material/${this.material.id}/simdut`
    window.open(simdutUrl, "_blank")
  }
}
