import {Component} from '@angular/core';
import {SubscribingComponent} from "../../../shared/components/subscribing.component";
import {Recipe} from "../../../shared/model/recipe.model";
import {RecipeService} from "../../services/recipe.service";
import {ActivatedRoute, Router} from "@angular/router";
import {FormBuilder, Validators} from "@angular/forms";
import {Subject} from "rxjs";
import {UNIT_GALLON, UNIT_LITER, UNIT_MILLILITER} from "../../../shared/units";
import {AccountService} from "../../../accounts/services/account.service";
import {EmployeePermission} from "../../../shared/model/employee";
import {EntityEditComponent} from "../../../shared/components/entity-edit/entity-edit.component";

@Component({
  selector: 'cre-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.sass']
})
export class EditComponent extends SubscribingComponent {
  readonly unitConstants = {UNIT_MILLILITER, UNIT_LITER, UNIT_GALLON}

  recipe: Recipe | null
  formFields = [
    {
      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: 'text',
      readonly: true,
      valueFn: recipe => recipe.company.name,
    }
  ]
  unknownError = false
  errorMessage: string | null
  units$ = new Subject<string>()

  constructor(
    private recipeService: RecipeService,
    private accountService: AccountService,
    router: Router,
    activatedRoute: ActivatedRoute
  ) {
    super(activatedRoute, router)
  }

  ngOnInit() {
    super.ngOnInit();

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

  changeUnits(unit: string) {
    this.units$.next(unit)
  }

  submit(editComponent: EntityEditComponent) {
    const values = editComponent.values
    this.subscribe(
      this.recipeService.update(this.recipe.id, values.name, values.description, values.sample, values.approbationDate, values.remark, this.recipe.steps),
      {
        next: () => this.router.navigate(['/color/list']),
        error: err => {
          if (err.status === 409) {
            this.errorMessage = `Une couleur avec le nom '${values.name}' et la bannière '${this.recipe.company.name}' existe déjà`
          } else {
            this.unknownError = true
            console.error(err)
          }
        }
      }
    )
  }

  delete() {
    this.subscribe(
      this.recipeService.delete(this.recipe.id),
      {
        next: () => this.router.navigate(['/color/list'])
      }
    )
  }

  get hasDeletePermission(): boolean {
    return this.accountService.hasPermission(EmployeePermission.REMOVE_RECIPE)
  }
}
