var booper = {
    overlayEl: undefined,
    overlayName: undefined,
    overlayTotal: undefined,
    overlay24h: undefined,
    targets: undefined,
};

let currentTimeout = 0;

let onImageTouch = function(target, relX, relY, pageX, pageY) {
    for (const [name, box] of Object.entries(target.locators)) {
        const [x1, y1, x2, y2] = box;
        if (relX >= x1 && relX <= x2 && relY >= y1 && relY <= y2) {
            console.log(`[booper.js] Booped ${name}!`);
            fetch(`/api/boop/${name}`, {method: 'POST'}).then((r) => {
                if (r.ok) {
                    r.json().then((json) => {
                        clearTimeout(currentTimeout);
                        booper.overlayName.innerText = name[0].toUpperCase()+name.slice(1);
                        booper.overlayTotal.innerText = json['total'];
                        booper.overlay24h.innerText = json['24h'];
                        booper.overlayEl.style.left = `${pageX}px`;
                        booper.overlayEl.style.top = `${pageY}px`;
                        booper.overlayEl.style.opacity = 1;
                        booper.currentTimeout = setTimeout(() => {
                            booper.overlayEl.style.opacity = 0;
                        }, 2000);
                        console.debug(json);
                    });
                } else {
                    console.error(`[booper.js] Error whilst booping:`);
                    console.error(r);
                }
            });
        }
    }
}

window.addEventListener('load', (e) => {
    booper.overlayEl = document.getElementById('booperOverlay');
    booper.overlayName = document.getElementById('booperName');
    booper.overlayTotal = document.getElementById('booperTotal');
    booper.overlay24h = document.getElementById('booper24h');
    booper.targets = document.getElementsByClassName('booperTarget');

    for (let i = 0; i < booper.targets.length; i++) {
        const target = booper.targets[i];
        const locators = JSON.parse(target.getAttribute('data-booper'));
        target.locators = locators;
        target.addEventListener('click', (e) => {
            let x = e.offsetX / e.originalTarget.clientWidth;
            let y = e.offsetY / e.originalTarget.clientHeight;
            onImageTouch(target, x, y, e.pageX, e.pageY);
        });
    }

    console.log(`[booper.js] Initialised ${booper.targets.length} boop target(s)!`);
});
