const FIVE_MINUTES = 1000 * 60 * 5;
const STORAGE_KEY = 'placeR-timestamp';
const colorPicker = document.getElementById('color');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const cellSize = 10;

// Fetch canvas initially and display its state
const response = await fetch('/api');
const prefill = await response.json();
for (let x = 0; x < prefill.length; x++) {
    for (let y = 0; y < prefill.length; y++) {
        ctx.fillStyle = prefill[x][y];
        ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
    }
}

ctx.fillStyle = colorPicker.value;

/**
 * Returns the cursor's position relative to the canvas
 *
 * @param {object} canvas - The canvas object
 * @param {object} event - The click event
 * @return {number[]} - x and y coordinates as number array
 */
function getCursorPosition(canvas, event) {
    const rect = canvas.getBoundingClientRect();
    const x = Math.floor((event.clientX - rect.left) / cellSize) * cellSize;
    const y = Math.floor((event.clientY - rect.top) / cellSize) * cellSize;
    return [x, y];
}

// Registering event listeners
colorPicker.addEventListener('input', () => {
    console.log('INPUT', colorPicker.value)
    ctx.fillStyle = colorPicker.value;
});

canvas.addEventListener('click', (event) => {
    // Check if user is allowed to set pixel based on time since last
    const lastStamp = +localStorage.getItem(STORAGE_KEY)
    if (lastStamp) {
        const due = Date.now() - lastStamp

        if (due < FIVE_MINUTES) {
            alert('You can place another pixel in ' + Math.floor((FIVE_MINUTES - due) / 1000) + ' seconds!')
            return
        }
    }

    localStorage.setItem(STORAGE_KEY, Date.now().toString())

    // Optimistically set pixel and send request
    const cursorPosition = getCursorPosition(canvas, event)
    ctx.fillRect(...cursorPosition, cellSize, cellSize);
    fetch(`/api?x=${cursorPosition[0]}&y=${cursorPosition[1]}`, {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({color: colorPicker.value})
    })
});
