import { IColumnProps } from "../IColumnProps";
import { Row } from "./Row";
import {
  viewportStartContext,
  viewportSizeContext,
} from "../context/ViewportContext";
import React from "react";

/**
 * This component render all the data rows in the table. Only as many rows as
 * can fit on the screen are ever rendered. These rows are moved around and
 * reused as the table scrolls to minimize rerendering
 */
export const Rows = <TRow, TChange, TError>({
  numStickyColumns,
  rows,
  columnProps,
  numHeaders,
  errors,
  numUnselectableColumns,
}: {
  numStickyColumns: number;
  rows: TRow[];
  columnProps: IColumnProps<TRow, TChange, TError>[];
  numHeaders: number;
  errors: (TError | null)[][];
  numUnselectableColumns: number;
}) => {
  const viewportStart = viewportStartContext.useState();
  const viewportSize = viewportSizeContext.useState();
  return (
    <>
      {[...new Array(viewportSize)].map((_, y) => {
        // actualY is the row index in the data and in the grid, since y is
        // never higher than the number of rows that can fit on the screen
        const actualY =
          Math.ceil((viewportStart - y) / viewportSize) * viewportSize + y - 1;
        return (
          <Row
            y={actualY}
            row={rows[actualY]}
            key={y}
            columnProps={columnProps}
            numStickyColumns={numStickyColumns}
            numHeaders={numHeaders}
            errors={errors[actualY]}
            numUnselectableColumns={numUnselectableColumns}
          />
        );
      })}
    </>
  );
};
