import {JSDOM} from 'jsdom';
import createVerovioModule from 'verovio/wasm';
import {readFile} from 'node:fs/promises';
import {VerovioToolkit} from 'verovio/esm';

const processOutput = (xmlData: string) => {
	const jsdom = new JSDOM(xmlData, { pretendToBeVisual: true, contentType: 'image/svg+xml' });
	const win = jsdom.window;

	const [svgElemsRoot, svgElemsMain] = Array.from(win.document.getElementsByTagName('svg'));
	if (typeof svgElemsRoot === 'undefined') {
		return '';
	}

	if (typeof svgElemsMain === 'undefined') {
		return '';
	}

	Array.from(svgElemsRoot.children).forEach((h) => {
		if (h !== svgElemsMain) {
			h.remove();
			if (h.tagName.toLowerCase() === 'desc') {
				return;
			}
			if (h.tagName.toLowerCase() === 'style') {
				h.innerHTML = h.innerHTML.replace(/font-family:(.+?);/g, '');
				h.innerHTML += 'path,polygon,text{fill:currentColor;}';
			}
			if (svgElemsMain.children[0]) {
				svgElemsMain.insertBefore(h, svgElemsMain.children[0]);
				return;
			}
			svgElemsMain.appendChild(h);
		}
	});

	Array.from(win.document.getElementsByClassName('pgHead')).forEach(h => {
		h.remove();
	});

	Array.from(win.document.getElementsByClassName('pgFoot')).forEach(h => {
		h.remove();
	});

	svgElemsMain.removeAttribute('color');

	return svgElemsMain.outerHTML;
	// return `<?xml version="1.0" encoding="utf-8"?>${svgElemsMain.outerHTML}`
};

export const loadScore = async (id: string) => {
	const verovioModule = await createVerovioModule();
	const score = await readFile(`public/scores/${id}.musicxml`, 'utf-8');
	const verovioToolkit = new VerovioToolkit(verovioModule);
	const isSuccessful = verovioToolkit.loadData(score);
	let raw = '';
	if (isSuccessful) {
		verovioToolkit.setOptions({
			breaks: 'none',
			font: 'Bravura',
			bottomMarginHeader: 0,
			bottomMarginArtic: 0,
			bottomMarginHarm: 0,
			topMarginHarm: 0,
			topMarginArtic: 0,
			topMarginPgFooter: 0,
			pageMarginTop: 0,
			pageMarginBottom: 0,
			pageMarginRight: 0,
			pageMarginLeft: 0,
			defaultBottomMargin: 0,
			defaultTopMargin: 0,
			defaultLeftMargin: 0,
			defaultRightMargin: 0,
		});

		try {
			raw = verovioToolkit.renderToSVG(1)
				.replace(/xmlns:mei="(.+?)"/g, '')
				.replace(/xlink:/g, '');
		} catch (err) {
			console.error(err);
		}

		return processOutput(raw);
	}

	return '';
};
