import React, { useContext, useEffect } from "react";
import { parse } from "url";
import { GetServerSideProps } from "next";
import Head from "next/head";

import { LogHeader, listLogs, LogFilter, logFilterFromQueryString } from "../../lib/rpdata/logs";
import gqlSsrClient from "../../lib/client/graphql-ssr";
import LogListContext, { LogListContextProvider } from "../../hooks/LogListContext";

interface LogsPageProps {
  headers: LogHeader[]
  filter: LogFilter
};

export default function LogsPage(props: LogsPageProps) {
  return (
    <LogListContextProvider initialFilter={props.filter} initialHeader={props.headers}>
      <Head>
        <title>Logs - Aite RP</title>
      </Head>
      <LogList />
    </LogListContextProvider>
  );
}

function LogList() {
  const {headers, filter, updateFilter} = useContext(LogListContext);

  useEffect(() => {
    const timeout = setTimeout(() => {
      updateFilter({...filter, limit: 10});
    }, 3000);

    return () => clearTimeout(timeout);
  }, [updateFilter]);

  return (
    <>
      <ol>
        {headers.map(l => <li key={l.shortId}>{l.title || `${l.channelName} — ${l.date}`}</li>)}
      </ol>
      <pre>{JSON.stringify(filter, null, 4)}</pre>
    </>
  );
}

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const u = parse(ctx.req.url);
  const filter = logFilterFromQueryString(u.search || "");

  const headers = await listLogs(gqlSsrClient, filter)
  return {
    props: {
      filter,
      headers,
    },
  };
} 

export const experimental = {
  trailingSlash: true
}