import {
	DOMParser,
	Document,
} from "https://deno.land/x/deno_dom@v0.1.38/deno-dom-wasm.ts";
import { assert } from "https://deno.land/std/testing/asserts.ts";

function energy(_str: any, energyType: string, _offset: any, _s: any): string {
	return `<img class="ptcg-energy-icon" src="/ptcg/${energyType}.svg" alt="${energyType}"/>`
}

function ptcg_icons(
	document: Document,
) {
	const regex = /\[(C|D|F|G|L|M|N|P|R|W)\]/g;
	const elements = Array();

	const decks = document.querySelectorAll('.ptcg-deck');
	decks.forEach(deck => {
		const titles = deck.querySelectorAll('.ptcg-label');
		elements.push(...titles);

		const names = deck.querySelectorAll('.name');
		elements.push(...names);

		const abilityEffects = deck.querySelectorAll('.ability-effect')
		elements.push(...abilityEffects);

		const attackCosts = deck.querySelectorAll('.attack-cost')
		elements.push(...attackCosts);

		const effects = deck.querySelectorAll('.effect')
		elements.push(...effects);
	});

	const cards = document.querySelectorAll('.ptcg-card');
	cards.forEach(card => {
		const names = card.querySelectorAll('.name');
		elements.push(...names);

		const abilityEffects = card.querySelectorAll('.ability-effect')
		elements.push(...abilityEffects);

		const attackCosts = card.querySelectorAll('.attack-cost')
		elements.push(...attackCosts);

		const effects = card.querySelectorAll('.effect')
		elements.push(...effects);
	});
	elements.forEach(element => {
		element.innerHTML = element.innerHTML.replace(regex, energy);
	});
}

async function process_file(filename: string): Promise<void> {
	const decoder = new TextDecoder();
	const document = new DOMParser().parseFromString(
		decoder.decode(await Deno.readFile(filename)),
		"text/html",
	)!;

	ptcg_icons(document);

	assert(document.documentElement !== null);
	await Deno.writeTextFile(filename, '<!DOCTYPE html>' + document.documentElement.outerHTML);
}

const filenames = Deno.args;
for (const filename of filenames) {
	await process_file(filename);
}
