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 { SearchUnit } from '../unit.model';
import { SearchFormService } from 'app/entities/shared/shared-search-form.service';

/**
 * Type for createFormGroup and resetForm argument.
 * It accepts SearchUnit, for search. in the list
 */
type UnitSearchFormGroupInput = SearchUnit;

type UnitSearchFormDefaults = SearchUnit;

type UnitSearchFormGroupContent = {
  id: FormControl<SearchUnit['id']>;
  code: FormControl<SearchUnit['code']>;
  name: FormControl<SearchUnit['name']>;
  symbol: FormControl<SearchUnit['symbol']>;
  description: FormControl<SearchUnit['description']>;
  version: FormControl<SearchUnit['version']>;
  unitTypeId: FormControl<SearchUnit['unitTypeId']>;
};

export type UnitSearchFormGroup = FormGroup<UnitSearchFormGroupContent>;

@Injectable({ providedIn: 'root' })
export class UnitSearchFormService extends SearchFormService {
  createUnitSearchFormGroup(unit: UnitSearchFormGroupInput = { id: null }): UnitSearchFormGroup {
    const unitRawValue = {
      ...this.getSearchFormDefaults(),
      ...unit,
    };
    return new FormGroup<UnitSearchFormGroupContent>({
      id: new FormControl(unitRawValue.id),
      code: new FormControl(unitRawValue.code),
      name: new FormControl(unitRawValue.name),
      symbol: new FormControl(unitRawValue.symbol),
      description: new FormControl(unitRawValue.description),
      version: new FormControl(unitRawValue.version),
      unitTypeId: new FormControl(unitRawValue.unitTypeId),
    });
  }

  getUnit(form: UnitSearchFormGroup): SearchUnit {
    return form.getRawValue() as SearchUnit;
  }

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

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

    return {
      id: null,
    };
  }
}
