import { useTableOptions } from 'client/hooks/Calculation/useOptions';
import { useTableStatus } from 'client/hooks/Calculation/useStatus';
import { useTableValidation } from 'client/hooks/Calculation/useValidation';
import { useTableValue } from 'client/hooks/Calculation/useValue';
import { useStores } from 'client/hooks/useStores';
import { observer } from 'mobx-react-lite';

export default ({ Component: Table, ...props }) => {
  const { name: tableName, callbacks } = props;
  const ObservedTable = observer(Table);
  const { calculationStore } = useStores();
  const tableData = calculationStore.tables[tableName];
  return () => (
    <ObservedTable
      {...props}
      {...tableData}
      withTableValue={withTableValue(callbacks)}
    />
  );
};

const withTableValue =
  callbacks =>
  Component =>
  ({ tableName, rowIndex, propName, validation, ...props }) =>
    observer(() => {
      const { value, setCurrentValue } = useTableValue({
        tableName,
        rowIndex,
        propName,
        columnCallback: callbacks?.[propName],
      });
      const { status } = useTableStatus({ tableName, rowIndex, propName });
      const { validateStatus, message } = useTableValidation({
        tableName,
        rowIndex,
        propName,
        validation,
      });

      const { options, filter } = useTableOptions({
        tableName,
        rowIndex,
        propName,
      });

      return (
        <Component
          {...props}
          value={value}
          setCurrentValue={setCurrentValue}
          status={status}
          validateStatus={validateStatus}
          message={message}
          options={options}
          filter={filter}
        />
      );
    });
