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 { SearchInventory } from '../inventory.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 InventorySearchFormGroupInput = SearchInventory;

type InventorySearchFormDefaults = SearchInventory;

type InventorySearchFormGroupContent = {
  id: FormControl<SearchInventory['id']>;
  value: FormControl<SearchInventory['value']>;
  variableId: FormControl<SearchInventory['variableId']>;
  variableNameOrCode: FormControl<SearchInventory['variableNameOrCode']>;
  periodId: FormControl<SearchInventory['periodId']>;
  ownerId: FormControl<SearchInventory['ownerId']>;
  categoryId: FormControl<SearchInventory['categoryId']>;
  scopeId: FormControl<SearchInventory['scopeId']>;
};

export type InventorySearchFormGroup = FormGroup<InventorySearchFormGroupContent>;

@Injectable({ providedIn: 'root' })
export class InventorySearchFormService extends SearchFormService {
  createInventorySearchFormGroup(inventory: InventorySearchFormGroupInput = { id: null }): InventorySearchFormGroup {
    const inventoryRawValue = {
      ...this.getSearchFormDefaults(),
      ...inventory,
    };
    return new FormGroup<InventorySearchFormGroupContent>({
      id: new FormControl(inventoryRawValue.id),
      value: new FormControl(inventoryRawValue.value),
      variableId: new FormControl(inventoryRawValue.variableId),
      variableNameOrCode: new FormControl(inventoryRawValue.variableNameOrCode),
      ownerId: new FormControl(inventoryRawValue.ownerId),
      periodId: new FormControl(inventoryRawValue.periodId, {
        validators: [Validators.required],
      }),
      categoryId: new FormControl(inventoryRawValue.categoryId, {
        validators: [Validators.required],
      }),
      scopeId: new FormControl(inventoryRawValue.scopeId, {
        validators: [Validators.required],
      }),
    });
  }

  getInventory(form: InventorySearchFormGroup): SearchInventory {
    return form.getRawValue() as SearchInventory;
  }

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

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

    return {
      id: null,
    };
  }
}
