#include "lib/doc_page.h"

StringMap* already_shown_items;

void render_doc_params(StringList param_lines)
{
	if(param_lines.size() == 0)
		return;

	<><div class="params"><h3>Parameters</h3></>
	for(auto line : param_lines)
	{
		if(trim(line) == "")
			continue;
		String name = trim(nibble(line, ":"));
		String value = trim(line);
		<><div><b><?= name ?></b><?
		if(value != "")
		{
			?> : <?: doc_markdown_inline(value) ?><?
		}
		?></div></>
	}
	<></div></>
}

void render_doc_page(String page)
{
	(*already_shown_items)[page] = "Y";
	DocPage doc_page = load_doc_page(page);
	String title = doc_default_title(page);
	if(doc_page.title != "")
		title = doc_page.title;

	<><section class="doc-page"><div class="sig"><h2><?= title ?></h2></>
	if(doc_page.sig_lines.size() > 0)
	{
		<><pre><? print(join(doc_page.sig_lines, "\n")); ?></pre></>
	}
	<></div></>

	render_doc_params(doc_page.param_lines);

	if(trim(doc_page.content) != "")
	{
		<><div class="content"><?: markdown_to_html(doc_page.content) ?></div></>
	}
	<></section></>
}

void render_see_section(String name)
{
	StringList lines = split(file_get_contents("areas/" + name + ".txt"), "\n");
	s32 idx = 0;
	for(auto line : lines)
	{
		if(idx == 0)
		{
			<><h1><?= line ?></h1></>
		}
		else if(line != "")
		{
			render_doc_page(line);
		}
		idx += 1;
	}
}


RENDER(Request& context)
{
	StringMap shown_items;
	already_shown_items = &shown_items;

	<><html>
	<head>
		<link rel="stylesheet" href='style.css?v=<?= time() ?>'></link>
	</head>
	<body>
		<h1>
			UCE API
		</h1>
		<?

		for(auto file_name : ls("areas/"))
		{
			String ft = nibble(file_name, ".");
			render_see_section(ft);
		}

		?><h1>Other Functions and Data Structures</h1><?
		for(auto file_name : ls("pages/"))
		{
			String ft = nibble(file_name, ".");
			if((*already_shown_items)[ft] == "")
				render_doc_page(ft);
		}

		?>
	</body>
	</html></>
}
