import { $, sleep } from "bun";
import { albumStuffF, fetchAlbumStuff } from "../lib/CiderV2Playing";
import { execFile } from "child_process";
import { rmSync } from "fs";

const isKDE = process.env.XDG_CURRENT_DESKTOP === "KDE" ? true : false;

let x: albumStuffF | any = false;
try {
	x = (await fetchAlbumStuff()) as albumStuffF;
} catch {}

let releaseMode = process.argv[3] === "rel";
// console.log(process.argv[3],isKDE,releaseMode);

function notifyWithImage(
	song: string,
	artUrl: string,
	artist: string,
	album: string,
) {
	if (isKDE === true) {
		execFile("notify-send", [
			"-t",
			releaseMode ? "10" : "2000",
			"-a",
			"Now Playing",
			"-i",
			artUrl,
			song,
			`${artist}`, //<br/>${album !== "" ? `<small>${album}</small>` : ""}`
		]);
		return;
	}
	execFile("dunstify", [
		"-t",
		releaseMode ? "1" : "2000",
		"-r",
		"67676767",
		"-a",
		"ocbwoy3-whatsplaying",
		"-I",
		artUrl,
		song,
		`${artist}<br/>`, //${album !== "" ? `<small>${album}</small>` : ""}`
	]);
}

function notifyBasic(song: string, artist: string, album: string) {
	if (isKDE === true) {
		execFile("notify-send", [
			"-t",
			releaseMode ? "1" : "2000",
			"-a",
			"Now Playing",
			song,
			`${artist}`, //<br/>${album !== "" ? `<small>${album}</small>` : ""}`
		]);
		return;
	}
	execFile("dunstify", [
		"-t",
		releaseMode ? "1" : "2000",
		"-r",
		"67676767",
		"-a",
		"ocbwoy3-whatsplaying",
		song,
		`${artist}`, //<br/>${album !== "" ? `<small>${album}</small>` : ""}`
	]);
}

if (process.argv[2] === "waybar") {
	if (!x) {
		process.stdout.write(
			JSON.stringify({
				class: "hidden",
			}),
		);
		process.exit(0);
	}
	const y = x as albumStuffF;
	process.stdout.write(
		JSON.stringify({
			// text: `  ${y.artist} — ${y.song}`.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"),
			text: `  ${y.artist} — ${y.song}`
				.replaceAll("&", "&amp;")
				.replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;"),
			tooltip: `${y.album}`
				.replaceAll("&", "&amp;")
				.replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;"),
		}),
	);
}

if (process.argv[2] === "notif") {
	const y = x as albumStuffF;
	if (!x || !y.artUrl) process.exit(1);

	try {
		console.log(y.song, y.artUrl, y.artist, y.album);
		notifyWithImage(y.song, y.artUrl, y.artist, y.album);
	} catch {
		notifyBasic(y.song, y.artist, y.album);
		try {
			rmSync(y.artUrl);
		} catch {}
	}
}
