import React from "react";
import Head from "next/head";

const ReportPage = () => {
  const ref = React.useRef();
  const getReport = async () => {
    const resp = await fetch("/api/html").then((resp) => resp.json());
    ref.current.innerHTML = resp.html;
    const json: Record<string, string> = await fetch("/api/admin").then(
      (resp) => resp.json()
    );
    const table = ref.current.children[0];
    const tbody = table.children[table.children.length - 1];
    for (const tr_index in tbody.children) {
      const tr = tbody.children[tr_index];
      for (const td_index in tr.children) {
        const td = tr.children[td_index];
        if (td.tagName !== "TD") continue;
        const index = `${tr_index},${td_index}`;
        if (json[index] === undefined) continue;
        td.innerHTML = json[index];
      }
    }
  };
  React.useEffect(() => {
    getReport();
  }, []);
  return (
    <>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <button onClick={async () => getReport()}>Refresh</button>
        <div
          ref={ref}
          onInput={(event) => {
            console.log(event.currentTarget.innerHTML);
          }}
          contentEditable="true"
        ></div>
      </main>
    </>
  );
};

export default ReportPage;
