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

import { SearchFormService } from 'app/entities/shared/shared-search-form.service';

export interface ISearchPeriodSelector {
  periodId?: number | null;
}

type SearchPeriodSelector = ISearchPeriodSelector;

type PeriodSelectorSearchFormGroupInput = SearchPeriodSelector;

type PeriodSelectorSearchFormDefaults = SearchPeriodSelector;

type PeriodSelectorSearchFormGroupContent = {
  periodId: FormControl<SearchPeriodSelector['periodId']>;
};

export type PeriodSelectorSearchFormGroup = FormGroup<PeriodSelectorSearchFormGroupContent>;

@Injectable({ providedIn: 'root' })
export class PeriodSelectorSearchFormService extends SearchFormService {
  createPeriodSelectorSearchFormGroup(search: PeriodSelectorSearchFormGroupInput = { periodId: null }): PeriodSelectorSearchFormGroup {
    const searchRawValue = {
      ...this.getSearchFormDefaults(),
      ...search,
    };
    return new FormGroup<PeriodSelectorSearchFormGroupContent>({
      periodId: new FormControl(searchRawValue.periodId, {
        validators: [Validators.required],
      }),
    });
  }

  getSearchPeriodSelector(form: PeriodSelectorSearchFormGroup): SearchPeriodSelector {
    return form.getRawValue() as SearchPeriodSelector;
  }

  resetForm(form: PeriodSelectorSearchFormGroup, search: PeriodSelectorSearchFormGroupInput): void {
    const searchRawValue = { ...this.getSearchFormDefaults(), ...search };
    form.reset(
      {
        ...searchRawValue,
      } as any /* cast to workaround https://github.com/angular/angular/issues/46458 */,
    );
  }

  private getSearchFormDefaults(): PeriodSelectorSearchFormDefaults {
    return { };
  }
}
