import { fromFileUrl } from '@std/path'
import type { JSX } from 'preact'
import { EnumType } from '@cliffy/command'
import type { Template } from '../types.ts'

export const templates: Map<
	string,
	Template<
		(props: Record<string, unknown>) => JSX.Element,
		Record<string, unknown>
	>
> = new Map()

const templatesDirUrl = import.meta.resolve('../templates')
const templatesDir = fromFileUrl(templatesDirUrl)

//Load templates dynamicaly
for await (
	const template of Deno.readDir(templatesDir)
) {
	if (
		template.isFile &&
		template.name.endsWith('.tsx') &&
		!template.name.startsWith('_')
	) {
		const modPath = new URL(
			template.name,
			`${import.meta.resolve('../templates')}/`,
		)
		const mod = await import(modPath.href)
		templates.set(mod.default.name, mod.default)
	}
}

export const templateType = new EnumType([...templates.keys()])