import type { InputsType, FillStateArgsType } from './types';
import findPath from './_find-path';

const fillState = (args: FillStateArgsType) => {
  const { theForm, initialState, update, setFilledState, stateRef } = args;
  const filledState = JSON.parse(JSON.stringify(initialState));
  const nodeList = theForm.querySelectorAll('input, select, text-area');
  const elements = Array.from(nodeList) as InputsType[];
  elements.forEach((elem) => {
    const name = (elem as InputsType).name;
    if (!name || (elem as HTMLElement).nodeName === 'FIELDSET') return;

    const path = findPath(elem as HTMLElement, theForm);
    let target = filledState;
    for (let i = 0; i < path.length; i++) {
      const prop = path[i]!;
      target[prop] = target[prop] || {};
      target = target[prop];
    }

    //TODO account for unchecked checkboxes (false not null)
    target[name] = typeof target[name] !== 'undefined' ? target[name] : null;

    update(filledState);

    stateRef.current = filledState;
    setFilledState(true);
  });
};

export default fillState;
