#!/bin/node
import {tree} from './tree.js'
import {
		rm,
		mkdir,
		writeFile,
		readFile,
		copyFile,
} from 'node:fs/promises';

import { dirname } from 'path'
import { fileURLToPath } from 'url'

import { JSDOM } from 'jsdom'

const __dirname = dirname(fileURLToPath(import.meta.url))

async function main() {
		// get tree data as json
		let treeData
		try {
				treeData = await tree()
		} catch(e) {
				console.error('Error building tree', e)
		}

		// remove the output folder
		const outDir = 'out'
		const currentDirPath = process.cwd()
		console.log('currentDirPath', currentDirPath)
		const outDirPath = `${currentDirPath}/${outDir}`
		try {
				await rm(outDirPath, { recursive: true, force: true })
		} catch(e) {
				console.error('Could not cleanly remove outDir', outDirPath, e)
		}

		const indexTemplatePath = `${__dirname}/templates/index.html`
		let indexTemplate
		try {
				const template = await readFile(indexTemplatePath, 'utf-8')
				const htmlTemplate = new JSDOM(template)
				const $body = htmlTemplate.window.document.querySelector('body')
				const $treeElement = htmlTemplate.window.document.createElement('tree-web')
				const $scriptElement = htmlTemplate.window.document.createElement('script')
				$scriptElement.setAttribute('async', true)
				$scriptElement.setAttribute('type', 'module')
				$scriptElement.setAttribute('src', './index.js')

				$body.append($treeElement)
				$body.append($scriptElement)
				indexTemplate = htmlTemplate.serialize()
		} catch(e) {
				console.error('Could not read html template file', indexTemplatePath, e)
		}

		// create a new output folder
		try {
				await mkdir(outDirPath)
		} catch(e) {
				console.error('Could not create outDir', outDirPath, e)
		}

		// save the tree data to json in the output folder/file
		const outFileName = 'index.json'
		const outFilePath = `${outDirPath}/${outFileName}`
		try {
				await writeFile(outFilePath, treeData)
		} catch(e) {
				console.error('Could not write tree data to json', outFilePath, e)
		}

		// write an index.html file
		const outIndexFileName = 'index.html'
		const outIndexFilePath = `${outDirPath}/${outIndexFileName}`
		try {
				await writeFile(outIndexFilePath, indexTemplate)
		} catch(e) {

				console.error('Could not copy HTML template', outFilePath, e)
		}

		// copy the tree web-component file
		const outScriptFileName = 'index.js'
		const outScriptFilePath = `${outDirPath}/${outScriptFileName}`
		try {
				await copyFile(`${__dirname}/web-components/tree-web.js`, outScriptFilePath)
		} catch(e) {
				console.error('Could not copy web-component', outScriptFilePath, e)
		}
}

main()
