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

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

type OutputDataSearchFormDefaults = SearchOutputData;

type OutputDataSearchFormGroupContent = {
  id: FormControl<SearchOutputData['id']>;
  variableId: FormControl<SearchOutputData['variableId']>;
  variableNameOrCode: FormControl<SearchOutputData['variableNameOrCode']>;
  periodId: FormControl<SearchOutputData['periodId']>;
  periodVersionId: FormControl<SearchOutputData['periodVersionId']>;
  ownerId: FormControl<SearchOutputData['ownerId']>;
  variableScopeId: FormControl<SearchOutputData['variableScopeId']>;
  variableCategoryId: FormControl<SearchOutputData['variableCategoryId']>;
};

export type OutputDataSearchFormGroup = FormGroup<OutputDataSearchFormGroupContent>;

@Injectable({ providedIn: 'root' })
export class OutputDataSearchFormService extends SearchFormService {
  createOutputDataSearchFormGroup(outputData: OutputDataSearchFormGroupInput = { id: null }): OutputDataSearchFormGroup {
    const outputDataRawValue = {
      ...this.getSearchFormDefaults(),
      ...outputData,
    };
    return new FormGroup<OutputDataSearchFormGroupContent>({
      id: new FormControl(outputDataRawValue.id),
      variableId: new FormControl(outputDataRawValue.variableId),
      variableNameOrCode: new FormControl(outputDataRawValue.variableNameOrCode),
      periodId: new FormControl(outputDataRawValue.periodId),
      periodVersionId: new FormControl(outputDataRawValue.periodVersionId),
      ownerId: new FormControl(outputDataRawValue.ownerId),
      variableScopeId: new FormControl(outputDataRawValue.variableScopeId),
      variableCategoryId: new FormControl(outputDataRawValue.variableCategoryId),
    });
  }

  getOutputData(form: OutputDataSearchFormGroup): SearchOutputData {
    return form.getRawValue() as SearchOutputData;
  }

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

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

    return {
      id: null,
    };
  }
}
