import {
	assert,
} from "qrc:/js/lib/utils";
import {
	getArticleName,
} from "qrc:/js/lib/graph_utils";

import {
	writeFile,
} from "./export_fs_util";

function escapeHtml(unsafe: string): string {
	return unsafe
		.replace(/&/g, "&amp;")
		.replace(/</g, "&lt;")
		.replace(/>/g, "&gt;")
		.replace(/"/g, "&quot;")
		.replace(/'/g, "&#039;");
}

function getResource(resource: string): string {
	const fileContent = wsi4.io.fs.readFile(resource);
	if (!fileContent) {
		assert(fileContent !== undefined, "Cannot read resource file \"" + resource + "\"");
	}
	return wsi4.util.arrayBufferToString(fileContent);
}

export function exportThreeDimHtml(cleanDirPath: string, vertex: Vertex, gltf: ArrayBuffer): string | undefined {
	const css = getResource(":/wsweb3d/wsweb3d.css");
	const js = getResource(":/wsweb3d/wsweb3d.js");
	const base64Content = wsi4.util.arrayBufferToString(wsi4.util.toBase64(gltf));

	const articleName = getArticleName(vertex);
	let html = "<!DOCTYPE html>\n";
	html += "<html lang=\"en\">\n";
	html += "\t<head>\n";
	html += "\t\t<meta charset=\"utf-8\">\n";
	html += "\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n";
	html += "\t\t<title>WSi4 - " + escapeHtml(articleName) + "</title>\n";
	html += "\t\t<style>" + css + "</style>\n";
	html += "\t\t<script>" + js + "</script>\n";
	html += "\t\t<script>document.addEventListener(\"DOMContentLoaded\", () => {\n";
	html += "\t\t\tconst c = \"" + base64Content + "\";\n";
	html += "\t\t\tconst r = new window.wsweb3d.default(document.getElementById(\"renderer\"), true);\n";
	html += "\t\t\tr.display(c); });\n";
	html += "\t\t</script>\n";
	html += "\t</head>\n";
	html += "\t<body>\n";
	html += "\t\t<div id=\"renderer\" style=\"width: 100%; height: 100%\"></div>\n";
	html += "\t</body>\n";
	html += "</html>\n";

	const fileName = articleName;
	const extension = "html";
	return writeFile(cleanDirPath, fileName, extension, wsi4.util.stringToArrayBuffer(html));
}
