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

import dayjs from 'dayjs/esm';
import { DATE_TIME_FORMAT } from 'app/config/input.constants';
import { SearchUnitConverter } from '../unit-converter.model';
import { SearchFormService } from 'app/entities/shared/shared-search-form.service';

/**
 * Type for createFormGroup and resetForm argument.
 * It accepts SearchInputData, for search. in the list
 */
type UnitConverterSearchFormGroupInput = SearchUnitConverter;

type UnitConverterSearchFormDefaults = SearchUnitConverter;

type UnitConverterSearchFormGroupContent = {
  id: FormControl<SearchUnitConverter['id']>;
  name: FormControl<SearchUnitConverter['name']>;
  description: FormControl<SearchUnitConverter['description']>;
  fromUnitId: FormControl<SearchUnitConverter['fromUnitId']>;
  toUnitId: FormControl<SearchUnitConverter['toUnitId']>;
};

export type UnitConverterSearchFormGroup = FormGroup<UnitConverterSearchFormGroupContent>;

@Injectable({ providedIn: 'root' })
export class UnitConverterSearchFormService extends SearchFormService {
  createUnitConverterSearchFormGroup(unitConverter: UnitConverterSearchFormGroupInput = { id: null }): UnitConverterSearchFormGroup {
    const unitConverterRawValue = {
      ...this.getSearchFormDefaults(),
      ...unitConverter,
    };
    return new FormGroup<UnitConverterSearchFormGroupContent>({
      id: new FormControl(unitConverterRawValue.id),
      name: new FormControl(unitConverterRawValue.name),
      description: new FormControl(unitConverterRawValue.description),
      fromUnitId: new FormControl(unitConverterRawValue.fromUnitId),
      toUnitId: new FormControl(unitConverterRawValue.toUnitId),
    });
  }

  getUnitConverter(form: UnitConverterSearchFormGroup): SearchUnitConverter {
    return form.getRawValue() as SearchUnitConverter;
  }

  resetForm(form: UnitConverterSearchFormGroup, unitConverter: UnitConverterSearchFormGroupInput): void {
    const unitConverterRawValue = { ...this.getSearchFormDefaults(), ...unitConverter };
    form.reset(
      {
        ...unitConverterRawValue,
        id: { value: unitConverterRawValue.id, disabled: true },
      } as any /* cast to workaround https://github.com/angular/angular/issues/46458 */,
    );
  }

  private getSearchFormDefaults(): UnitConverterSearchFormDefaults {
    const currentTime = dayjs();

    return {
      id: null,
    };
  }
}
