import { PluginListener } from "@tauri-apps/api/core";
import { readFile } from "@tauri-apps/plugin-fs";
import { createEffect } from "solid-js";
import { listenForShareEvents, ShareEvent } from "tauri-plugin-sharetarget-api";
import { sendImageFile } from "../network";
import { platform } from "@tauri-apps/plugin-os";

const currentPlatform = platform();

export const onAndroidMount = () => {
	createEffect(() => {
		if (currentPlatform !== "android") {
			return;
		}

		let listener: PluginListener;

		const setupListener = async () => {
			console.log("Setting up listener");

			listener = await listenForShareEvents(async (intent: ShareEvent) => {
				console.log(intent);
				const contents = await readFile(intent.stream ?? "").catch(
					(error: Error) => {
						console.warn("fetching shared content failed:");
						throw error;
					},
				);

				const f = new File([contents], intent.name ?? "no-name", {
					type: intent.content_type,
				});

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

		setupListener();
		return () => {
			listener?.unregister();
		};
	});
};
