import { readFile } from "@tauri-apps/plugin-fs";
import { type Component, createEffect, createSignal, Show } from "solid-js";
import { listenForShareEvents } from "tauri-plugin-sharetarget-api";
import { sendImageFile } from "../../network";

export const ShareTarget: Component = () => {
    const [file, setFile] = createSignal<File>();

    createEffect(() => {
        const listener = listenForShareEvents(async (intent) => {
            if (intent.stream == null) {
                throw new Error(
                    "The shared item does not have a stream to read form. This might be an issue with the type of file that was shared.",
                );
            }

            if (intent.name == null) {
                throw new Error("The shared item does not have a name.");
            }

            const contents = await readFile(intent.stream);

            setFile(
                new File([contents], intent.name, {
                    type: intent.content_type,
                }),
            );
        });

        return () => {
            listener.then((l) => l.unregister());
        };
    });

    // TODO: This might be made better by just sending the file without setting it.
    // And simply displaying a message or not displaying anything really.
    createEffect(() => {
        const f = file();
        if (f == null) {
            return;
        }

        sendImageFile(f.name, f);
    });

    return <Show when={file()}>{(f) => <p>Name: {f().name}</p>}</Show>;
};
