import {Component, EventEmitter, Input, Output} from '@angular/core';
import {SubscribingComponent} from "../subscribing.component";
import {FormBuilder, FormControl, FormGroup, ValidatorFn} from "@angular/forms";
import {Observable} from "rxjs";
import {ActivatedRoute, Router} from "@angular/router";

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

  form: FormGroup | null

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

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

    super.ngOnInit();
  }

  submitForm() {
    const values = {}
    this.formFields.forEach(f => {
      values[f.name] = this.getControl(f.name).value
    })
    this.submit.emit(values)
  }

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

export class FormField {
  constructor(
    public name: string,
    public label?: string,
    public icon?: string,
    public type?: string,
    public validator?: ValidatorFn,
    public errorMessages?: FormErrorMessage[],
    public valueFn?: (any) => any,
    public template?: any,
    public readonly?: boolean,
    // Specifics to some types
    public step?: string,
    public options$?: Observable<{ value: any, label: string }[]>,
    public fileType?: string
  ) {
  }
}

export class FormErrorMessage {
  constructor(
    public conditionFn: (any) => boolean,
    public message: string
  ) {
  }
}
