import {Component, EventEmitter, Input, Output} from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
import {SubscribingComponent} from "../subscribing.component";
import {FormField} from "../entity-add/entity-add.component";
import {EmployeePermission} from "../../model/employee";
import {AccountService} from "../../../accounts/services/account.service";
import {ActivatedRoute, Router} from "@angular/router";

@Component({
  selector: 'cre-entity-edit',
  templateUrl: './entity-edit.component.html',
  styleUrls: ['./entity-edit.component.sass']
})
export class EntityEditComponent extends SubscribingComponent {
  @Input() entity: any
  @Input() title: string
  @Input() deleteConfirmMessage: string
  @Input() backButtonLink: string
  @Input() formFields: FormField[]
  @Input() deletePermission: EmployeePermission
  @Input() unknownError = false
  @Input() customError: string | null
  @Input() disableButtons: boolean
  @Output() submit = new EventEmitter<any>()
  @Output() delete = new EventEmitter<void>()

  form: FormGroup | null

  constructor(
    private accountService: AccountService,
    private formBuilder: FormBuilder,
    router: Router,
    activatedRoute: ActivatedRoute
  ) {
    super(activatedRoute, router)
  }

  ngOnInit() {
    const formGroup = {}
    this.formFields.forEach(f => {
      formGroup[f.name] = new FormControl(f.valueFn ? f.valueFn(this.entity) : this.entity[f.name], f.validator)
    })
    this.form = this.formBuilder.group(formGroup)

    super.ngOnInit();
  }

  submitForm() {
    this.submit.emit(this.values)
  }

  getControl(controlName: string): FormControl {
    return this.form.controls[controlName] as FormControl
  }

  get values(): any {
    const values = {}
    this.formFields.forEach(f => {
      values[f.name] = this.getControl(f.name).value
    })
    return values
  }

  get canDelete(): boolean {
    return this.accountService.hasPermission(this.deletePermission)
  }
}
