//-		DS2 core (c) 2024 Alexander McIlwraith 
//-		Licensed under CC BY-SA 4.0 

const font = {
	size: 0
}

const pos = {
	x: 0,
	y: 0
}

function drag(sticky) {
	sticky.onmousedown = event => {
		// get the position within the sticky
		pos.x = (event.clientX - sticky.offsetLeft);
		pos.y = (event.clientY - sticky.offsetTop);

		// on mouse move, move the sticky to the position, minus the offset, of the mouse
		document.onmousemove = documentEvent => {
			sticky.style.top = (documentEvent.clientY - pos.y) + 'px';
			sticky.style.left = (documentEvent.clientX - pos.x) + 'px';
			sticky.setAttribute("moved", "true");
		}
		// when done, remove mouse move and mouse up handlers. 
		document.onmouseup = () => {
			document.onmouseup = null;
			document.onmousemove = null;
		}
	}
}

function waitForElement(selector) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                observer.disconnect();
                resolve(document.querySelector(selector));
            }
        });

        // If you get "parameter 1 is not of type 'Node'" error, see https://stackoverflow.com/a/77855838/492336
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}

const checkBottom = (attach) => {
	// check if top or bottom
	if (attach.y < 0) { 
		attach.ys = "bottom";
		attach.y = attach.y * -1;
	}
}

const setStickyPostions = (s, attach) => {
		// set 
		s.style[attach.ys] = `${attach.y}px`;
		s.style[attach.xs] = `${attach.x}px`;
		s.style.display = "grid";
}

const css = (el, attr) => {
	let st = ""
	Object.entries(attr).forEach(val => {
		const [key, value] = val;
  		st += `${key}: ${value}; `;
	})
  	el.setAttribute("style",st.trim());
}


const calculateStickyPosition = (s) => {
	let float = s.getAttribute("float");
	let p = s.parentNode.getBoundingClientRect()
	switch (float) {
		case "left": 
			css(s, {left: (p.left * -1) + "px"})
			break;
		case "right":
			css(s, { left: (Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) - p.left - s.offsetWidth - (font.size * 2)) + "px" }); 
			break;
	} 

	let offset = s.getAttribute("offset");
	if (offset !== null) {
		offset = offset.trim().split(" ");
		css(s, {top: offset[0], left: offset[1] })
	}
}

module.exports = {
	init: (p = document) => {
		font.size = parseFloat(getComputedStyle(document.documentElement).fontSize.replace("px",""));

		p.querySelectorAll("sticky-note").forEach((s) => {
			if (s.querySelectorAll("svg").length == 0) {
				
				let wrapper = document.createElement("sticky-note-wrapper");

				s.parentNode.insertBefore(wrapper, s);
	    		wrapper.appendChild(s);

				s.setAttribute("content", s.innerHTML.replace(/"/g, "\""));
				s.innerHTML = `<div><svg width='0' height='0'><defs><clipPath id='stickyClip' clipPathUnits='objectBoundingBox'><path d='M 0 0 Q 0 0.69, 0.03 0.96 0.03 0.96, 1 0.96 Q 0.96 0.69, 0.96 0 0.96 0, 0 0' stroke-linejoin='round' stroke-linecap='square' /></clipPath></defs></svg></div><div><div>${s.innerHTML}</div></div>`;
			}
			calculateStickyPosition(s);
			drag(s);
			s.ondblclick = (e) => {
				if (e.ctrlKey) {
					calculateStickyPosition(s);
				} else {
					// add one click select
				}
			}
		})


		window.onresize = () => {
			font.size = parseFloat(getComputedStyle(document.documentElement).fontSize.replace("px",""));
			let stickies = p.querySelectorAll("sticky-note");
			stickies.forEach((s) => {
				calculateStickyPosition(s);
			});
		}
	}
}