import { client } from "@/client";
import { useLoading } from "@/hooks/useLoading.ts";
import { AttachmentId, PieceId } from "common";
import { OpenSheetMusicDisplay } from "opensheetmusicdisplay";
import { useEffect, useRef } from "react";
import { useParams } from "react-router-dom";

export default function Attachment() {

	const params = useParams();
	const pieceId = PieceId(params.pieceId!);
	const attachmentId = AttachmentId(params.attachmentId!);

	const { isLoading, error, data } = useLoading(() => client.piece({ pieceId }).attachment({ attachmentId }).get());

	const containerRef = useRef<HTMLDivElement>(null);

	useEffect(() => {
		if (isLoading || error !== null) return;

		const url = URL.createObjectURL(data?.data);

		const render = () => osmd.render();

		const osmd = new OpenSheetMusicDisplay(containerRef.current!, {
			autoResize: false,
			drawTitle: false,
			drawComposer: false,
			drawMeasureNumbers: true,
			drawMeasureNumbersOnlyAtSystemStart: true,
			//measureNumberInterval: 5,
			//renderSingleHorizontalStaffline: true,
		});

		osmd.load(url).then(render);

		window.addEventListener("resize", render);

		return () => {
			URL.revokeObjectURL(url);
			window.removeEventListener("resize", render);
		};
	}, [isLoading, data]);

	if (isLoading) {
		return (
			<div className="w-full h-full overflow-hidden flex items-center justify-center">
				<div>Ładowanie…</div>
			</div>
		);
	}

	if (error !== null) {
		<div className="w-full h-full overflow-hidden flex items-center justify-center">
			<div>Wystąpił błąd: {error.value}</div>
		</div>
	}

	return <div ref={containerRef} className="w-full h-full overflow-scroll" />;
};
