import fs from "node:fs"
import path from "node:path"
import cors from "@fastify/cors"
import fastifyStatc from "@fastify/static"
import dayjs from "dayjs"
import Fastify from "fastify"
import React from "react"
import { renderToStaticMarkup } from "react-dom/server"
import { estaticos } from "../src"
import { ambiente } from "./ambiente"
import { gerar } from "./listar_arquivos"

// gambi para fazer funcionar
React

const { PORTA, PREFIXO } = ambiente

const _iframe = String(Math.random())

const criarHtml = (entrada: {
  [key: string]: string | {}
}): React.JSX.Element[] => {
  const retorno = [] as React.JSX.Element[]

  for (const [k, v] of Object.entries(entrada)) {
    if (typeof v === "string") {
      retorno.push(
        <p key={Math.random()}>
          <a
            target={_iframe}
            href={`${v}?aleatório=${Math.random()}`}
          >
            {v}
          </a>
        </p>,
      )
    } else {
      retorno.push(
        <div
          key={Math.random()}
          style={{
            margin: 10,
            padding: 5,
            borderColor: "black",
            borderWidth: "1px",
            borderStyle: "solid",
          }}
        >
          <details>
            <summary>{k}</summary>
            {criarHtml(v)}
          </details>
        </div>,
      )
    }
  }

  return retorno
}

gerar.then(() => {
  const fastify = Fastify({
    logger: false,

    ignoreTrailingSlash: true,
  })

  fastify.addHook("onSend", async (request, reply) => {
    console.log(
      [
        dayjs().format("YYYY-MM-DD HH:mm:ss"),
        request.method,
        request.url,
        reply.statusCode,
        request.headers.site || request.headers.referer,
      ].join("  "),
    )
  })

  //cors
  fastify.register(cors, {
    origin: "*",
  })

  fastify.route({
    method: "GET",
    url: "/",
    handler: (_req, res) => {
      res.redirect(`${PREFIXO}/`)
    },
  })

  fastify.route({
    method: "GET",
    url: `${PREFIXO}/`,
    handler: async (_request, reply) => {
      const html = (
        <html lang="pt-BR">
          <head>
            <title>Arquivos Estáticos</title>
          </head>{" "}
          <body>
            <h4>Arquivos Estáticos</h4>
            <table width={"100%"}>
              <tr>
                <td width={"50%"}> {criarHtml(estaticos("relativo"))} </td>
                <td width={"50%"}>
                  <iframe
                    title="Iframe"
                    name={_iframe}
                    height={600}
                    width={"100%"}
                  />
                </td>
              </tr>
            </table>
          </body>
        </html>
      )

      const renderHtml = renderToStaticMarkup(html, {})

      // htlm utf-8
      reply.header("content-type", "text/html; charset=utf-8")
      reply.send(renderHtml)
    },
  })

  fastify.register(fastifyStatc, {
    root: path.join(process.cwd(), "estaticos"),
    prefix: PREFIXO,
  })

  // 404
  fastify.setNotFoundHandler((request, reply) => {
    const html404 = fs.readFileSync(
      path.join(process.cwd(), estaticos("relativo").html["404.html"]),
      "utf8",
    )

    reply.header("content-type", "text/html; charset=utf-8")

    reply
      .code(404)
      .send(html404.replace("{ERRO}", `Página não encontrada: ${request.url}`))
  })

  const jaEstaRodando = fetch(`http://0.0.0.0:${PORTA}`)
    .then(() => true)
    .catch(() => false)

  jaEstaRodando.then((jaEstaRodando) => {
    !jaEstaRodando &&
      fastify.listen(
        { port: Number(PORTA), host: "0.0.0.0" },
        (err, address) => {
          if (err) throw err
          console.log(
            `${new Date().toISOString()} Servidor ${PREFIXO} Rodando em ${address}`,
          )
        },
      )

    jaEstaRodando && console.log(`Servidor ${PREFIXO} já está rodando`)
  })
})
