import {Component} from '@angular/core';
import {SubscribingComponent} from "../../../shared/components/subscribing.component";
import {Company} from "../../../shared/model/company.model";
import {FormField} from "../../../shared/components/entity-add/entity-add.component";
import {Validators} from "@angular/forms";
import {CompanyService} from "../../service/company.service";
import {ActivatedRoute, Router} from "@angular/router";

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

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

  ngOnInit(): void {
    super.ngOnInit()

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

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

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