function createQrCode(elementId, data, width, height) {
    new QRCode(document.getElementById(elementId),
        {
            text: data,
            width: width,
            height: height
        });
}
function clearQrCode(elementId) {
    var qrc = document.getElementById(elementId);
    qrc.innerHTML = '';
    qrc.title = '';
}

async function displayScreenData(screenId, viewWidth, viewHeight, left, top, width, height, buffer) {

    const screenDiv = document.getElementById(screenId);

    if (screenDiv.width !== viewWidth || screenDiv.height !== viewHeight) {
        screenDiv.width = viewWidth;
        screenDiv.height = viewHeight;
    }

    const ctx = screenDiv.getContext('2d');

    const imageBlob = new Blob([buffer], { type: 'image/bitmap' });

    try {
        const bitmap = await createImageBitmap(imageBlob);
        ctx.drawImage(bitmap, left, top, width, height);
        bitmap.close();
    } catch (err) {
        console.error("Error creating image bitmap:", err);
    }
}

async function updateCursor(screenId, cursorId, hotSpotX, hotSpotY, icon) {

    const screenDiv = document.getElementById(screenId);
    const cursorDiv = document.getElementById(cursorId);

    if (cursorDiv.width !== screenDiv.width || cursorDiv.height !== screenDiv.height) {
        cursorDiv.width = screenDiv.width;
        cursorDiv.height = screenDiv.height;
    }

    if (cursorDiv.style.marginLeft !== `-${screenDiv.clientWidth}px`) {
        cursorDiv.style.marginLeft = `-${screenDiv.clientWidth}px`;
    }

    const ctx = cursorDiv.getContext('2d');
    ctx.clearRect(0, 0, cursorDiv.width, cursorDiv.height);

    if (icon) {
        const iconBuffer = new Blob([icon], { type: 'image/png' });

        const bitmap = await createImageBitmap(iconBuffer);
        ctx.drawImage(bitmap, hotSpotX, hotSpotY, 32, 32);
        bitmap.close();
    }
    else {
        ctx.fillStyle = 'white';
        ctx.beginPath();
        ctx.arc(hotSpotX, hotSpotY, 10, 0, Math.PI * 2);
        ctx.fill();
    }
}

async function setupCursorEvents(dotNetReference, canvasId, methodName) {
    const canvas = document.getElementById(canvasId);
    if (canvas) {
        canvas.addEventListener('mousemove', function (event) {
            const rect = canvas.getBoundingClientRect();
            const x = event.clientX - rect.left;
            const y = event.clientY - rect.top;

            let scaleX = canvas.clientWidth / canvas.width;
            let scaleY = canvas.clientHeight / canvas.height;

            let adjustedX = x / scaleX;
            let adjustedY = y / scaleY;

            dotNetReference.invokeMethodAsync(methodName, adjustedX, adjustedY);
        });
    }
}