import { Data } from '../../../../types';
import {
  DynamicListReducerInitArgs,
  DynamicListReducerState,
} from './DynamicListReducer.types';

export const DynamicListReducerInit = <T extends Data>(
  args: DynamicListReducerInitArgs<T>,
): DynamicListReducerState<T> => {
  const { initialValue, positionPropertyName, maxItemLimit, allowNewData } =
    args;

  const newState: DynamicListReducerState<T> = {
    items: initialValue,
    nextPosition: 1,
    canAddItems: false,
    positionPropertyName,
    maxItemLimit,
    allowNewData,
  };

  if (positionPropertyName !== undefined && initialValue.length > 0) {
    const sortedValue = [...initialValue].sort(
      (a, b) =>
        Number(a[positionPropertyName]) - Number(b[positionPropertyName]),
    );

    newState.nextPosition =
      sortedValue[sortedValue.length - 1][positionPropertyName] + 1;

    newState.items = sortedValue;
  }

  newState.canAddItems =
    allowNewData &&
    ((maxItemLimit !== undefined && newState.items.length < maxItemLimit) ||
      maxItemLimit === undefined);

  return newState;
};
