/**
 * 休止符提示器
 * auth: lsq
 * time: 2022.11.14
 */

import { reactive } from "vue";

export const restPromptData = reactive({
	list: [] as any[],
});

export const restPromptMain = (times: any[]) => {
	calculateMergeRest(times);
};

// 计算合并的休止符小节
function calculateMergeRest(times: any[]) {
	// console.log(times);
	// 1. 统计所有休止的小节, 并记录五线谱休止符的小节位置和大小
	const measures: any[] = [];
	const osmdSvg: SVGAElement = document.querySelector('#osmdSvgPage1')!
	const viewBox = osmdSvg.getAttribute('viewBox')?.split(' ') || []
	let zoom: number = Number(osmdSvg.getAttribute('width')) / Number(viewBox[2])
	zoom = isNaN(zoom) ? 1 : zoom
	// console.log("🚀 ~ zoom", zoom)
	for (let i = 0; i < times.length; i++) {
		const note = times[i];
		const measureNumberXML = note?.noteElement?.sourceMeasure?.MeasureNumberXML || -1;
		const multipleRestMeasures = note?.noteElement?.sourceMeasure?.multipleRestMeasures || 0;
		const allRests = note?.noteElement?.sourceMeasure?.allRests || false;
		const hasMeasure = measures.find((n) => n.measureNumberXML === measureNumberXML);
		if (!hasMeasure && allRests && multipleRestMeasures > 1) {
			const staveBox = getStaveBox(note?.stave?.attrs?.id, zoom);
			// console.log("🚀 ~ note", note, stave);
			measures.push({
				measureNumberXML,
				allRests,
				multipleRestMeasures,
				staveBox,
			});
		}
	}
	// console.log(measures);
	restPromptData.list = measures;
}

// 获取休止符的位置
function getStaveBox(id: string, zoom: number){
    if (!id) return {}
    const stave = document.querySelector('#' + id)
    if (stave){
		const bbox = (stave?.nextElementSibling as SVGAElement)?.getBBox()
        return {
            left: bbox.x * zoom + 'px',
            top: bbox.y * zoom  + 'px',
            width: bbox.width * zoom  + 'px',
            height: bbox.height * zoom  + 'px'
        }
    }
    return {}
}
