import React from "react";
import { createRenderExtension } from "./base";
import { TableCell } from "mdast-util-gfm-table/lib";
import { MarkdownController } from "../libs/controller";
import { Table } from "../styled";

function renderCells(controller: MarkdownController, cells: TableCell[], maxCells?: number) {
  const realCells = maxCells != null ? cells.slice(0, maxCells) : cells;
  return realCells.map((content, index) => {
    return <td key={`cell-${index}`}>{controller.renderChildren(content.children)}</td>;
  });
}

export const extTable = createRenderExtension({
  renderContent(controller, content, next) {
    if (content.type === "table") {
      const length = content.align?.length;
      const [header, ...bodys] = content.children;

      const headerElem = (
        <thead>
          <tr>{renderCells(controller, header.children, length)}</tr>
        </thead>
      );
      const bodysElem = (
        <tbody>
          {bodys.map((child: any) => {
            const cells = child.children;
            return <tr>{renderCells(controller, cells, length)}</tr>;
          })}
        </tbody>
      );

      return (
        <Table>
          {headerElem}
          {bodysElem}
        </Table>
      );
    }
    return next();
  },
});
