import { listen } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { type Component, createEffect } from "solid-js";
import { sendImage } from "../network";

// This probably shouldn't live here.
// The request should be made from rust but hey.
// We'll do that later

export const ImageViewer: Component = () => {
    // const [latestImage, setLatestImage] = createSignal<string | null>(null);

    let sentImage = "";

    createEffect(async () => {
        // Listen for PNG processing events
        const unlisten = listen("png-processed", async (event) => {
            const base64Data = event.payload as string;

            if (base64Data === sentImage) {
                return;
            }

            sentImage = base64Data;

            const appWindow = getCurrentWindow();

            appWindow.show();
            appWindow.setFocus();

            // setLatestImage(`data:image/png;base64,${base64Data}`);

            const result = await sendImage("test-image.png", base64Data);

            console.log("DBG: ", result);
        });

        return () => {
            unlisten.then((fn) => fn()); // Cleanup listener
        };
    });

    return null;
};
