import { Injectable, inject } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray, FormBuilder } from '@angular/forms';

import { IVariableUnits, NewVariableUnits } from '../variable-units.model';
import { IUnitConverter } from 'app/entities/unit-converter/unit-converter.model';

/**
 * A partial Type with required key is used as form input.
 */
type PartialWithRequiredKeyOf<T extends { id: unknown }> = Partial<Omit<T, 'id'>> & { id: T['id'] };

/**
 * Type for createFormGroup and resetForm argument.
 * It accepts IVariableUnits for edit and NewVariableUnitsFormGroupInput for create.
 */
type VariableUnitsFormGroupInput = IVariableUnits | PartialWithRequiredKeyOf<NewVariableUnits>;

type VariableUnitsFormDefaults = Pick<NewVariableUnits, 'id'>;

type VariableUnitsFormGroupContent = {
  id: FormControl<IVariableUnits['id'] | NewVariableUnits['id']>;
  version: FormControl<IVariableUnits['version']>;
  variable: FormControl<IVariableUnits['variable']>;
  unit: FormControl<IVariableUnits['unit']>;
  unitConverter: FormControl<IVariableUnits['unitConverter']>;
  unitConverterOptions: FormControl<IUnitConverter[] | null>;
};

export type VariableUnitsFormGroup = FormGroup<VariableUnitsFormGroupContent>;

@Injectable({ providedIn: 'root' })
export class VariableUnitsFormService {
  protected fb = inject(FormBuilder);
  
  createVariableUnitsFormGroup(variableUnits: VariableUnitsFormGroupInput = { id: null }): VariableUnitsFormGroup {
    const variableUnitsRawValue = {
      ...this.getFormDefaults(),
      ...variableUnits,
    };
    return new FormGroup<VariableUnitsFormGroupContent>({
      id: new FormControl(
        { value: variableUnitsRawValue.id, disabled: true },
        {
          nonNullable: true,
          validators: [Validators.required],
        },
      ),
      version: new FormControl(variableUnitsRawValue.version),
      variable: new FormControl(variableUnitsRawValue.variable),
      unit: new FormControl(variableUnitsRawValue.unit, {validators: [Validators.required],}),
	  unitConverter: new FormControl(variableUnitsRawValue.unitConverter),
	  unitConverterOptions: new FormControl([]),
    });
  }

  getVariableUnits(form: VariableUnitsFormGroup): IVariableUnits | NewVariableUnits {
    return form.getRawValue() as IVariableUnits | NewVariableUnits;
  }

  resetForm(form: VariableUnitsFormGroup, variableUnits: VariableUnitsFormGroupInput): void {
    const variableUnitsRawValue = { ...this.getFormDefaults(), ...variableUnits };
    form.reset(
      {
        ...variableUnitsRawValue,
        id: { value: variableUnitsRawValue.id, disabled: true },
      } as any /* cast to workaround https://github.com/angular/angular/issues/46458 */,
    );
  }

  private getFormDefaults(): VariableUnitsFormDefaults {
    return {
      id: null,
    };
  }
}
