import initWasmModule, { post, like } from './wasm/wasm_mod.js';

(async () => {
    await initWasmModule();
})();


chrome.runtime.onMessage.addListener(async (request, sender, _) => {
    if (request?.action) {

        const storage = await chrome.storage.local.get();

        if (request.action == "like") {
            const { rect, ratio, by, me, id, is_private } = request;

            if (sender.tab) {
                // make a screenshot

                if (storage.screenshot) {
                    setTimeout(async function () {
                        const screenshot = await chrome.tabs.captureVisibleTab(null, { format: "png" });

                        const canvas = new OffscreenCanvas(rect.width, rect.height);

                        const bytes = atob(screenshot.replace("data:image/png;base64,", ""));
                        const array_buf = new ArrayBuffer(bytes.length);
                        const uint_arr = new Uint8Array(array_buf);
                        for (let i = 0; i < bytes.length; i++) {
                            uint_arr[i] = bytes.charCodeAt(i);
                        }

                        const blob = new Blob([array_buf], { type: "image/png" });
                        const top = Math.max(rect.top, 0);
                        const bitmap = await createImageBitmap(
                            blob,
                            Math.ceil(rect.left * ratio),
                            Math.ceil(top * ratio),
                            rect.width * ratio,
                            (rect.bottom - top) * ratio // if top of the image is outside of the viewport, subtract offset from height
                        );

                        canvas.getContext('bitmaprenderer').transferFromImageBitmap(bitmap);
                        const cropped_blob = await canvas.convertToBlob(); // slllloooow. kinda. 300ms.

                        const cropped_bytes = await cropped_blob.arrayBuffer();
                        const cropped_bytes_uint8 = new Uint8Array(cropped_bytes);

                        await like({ id, by, me, is_private }, cropped_bytes_uint8);
                    }, storage.delay || 1)

                } else {
                    await like({ id, by, me, is_private });
                }
            }
        }
    }
})
