import { estaticos } from "../src";
import path from "node:path";
import express from "express";
import fs from "node:fs";
import { gerar } from "./listar_arquivos";
import { ambiente } from "./ambiente";
import { renderToStaticMarkup } from "react-dom/server";

// biome-ignore lint/style/useImportType: <explanation>
import React, {} from "react";
const { PORTA, PREFIXO } = ambiente;

const _iframe = String(Math.random());

const criarHtml = (entrada: {
	// biome-ignore lint/complexity/noBannedTypes: <explanation>
	[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 open>
						<summary>{k}</summary>
						{criarHtml(v)}
					</details>
				</div>,
			);
		}
	}

	return retorno;
};

gerar.then(() => {
	const app = express();
	app.use(express.json());
	app.use(express.urlencoded());

	app.get([PREFIXO, `${PREFIXO}/`], (req, res) => {
		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, {});

		res.setHeader("content-type", "text/html");
		res.send(renderHtml);
	});
	app.get(`${PREFIXO}/*`, (req, res) => {
		const caminho_arquivo = path.join(process.cwd(), decodeURI(req.path));

		if (fs.existsSync(caminho_arquivo)) {
			console.log(`200: ${req.url}`);
			return res.sendFile(caminho_arquivo);
		}
		console.log(`404: ${req.url}`);
		return res.status(404).send(`404: ${req.url}`);
	});

	app.all("*", (req, res) => {
		res.redirect(PREFIXO);
	});

	app.listen(PORTA, () => {
		console.log(`Servidor ${PREFIXO} Rodando em http://localhost:${PORTA}`);
	});
});
