package com.dynamicwallpaper.core;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/** Applies a generated .heic file as the current desktop picture, via AppleScript. */
public final class WallpaperInstaller {

    private WallpaperInstaller() {
    }

    /**
     * Sets {@code heicFile} as the desktop picture on every display, using
     * System Events. This only touches the user's own desktop picture
     * setting and is reversible from System Settings at any time.
     */
    public static void setAsDesktopPicture(File heicFile) throws IOException, InterruptedException {
        String escapedPath = heicFile.getAbsolutePath()
                .replace("\\", "\\\\")
                .replace("\"", "\\\"");
        String script = "tell application \"System Events\" to tell every desktop to set picture to POSIX file \""
                + escapedPath + "\"";

        ProcessBuilder pb = new ProcessBuilder("osascript", "-e", script);
        pb.redirectErrorStream(true);
        Process process = pb.start();
        String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
        boolean finished = process.waitFor(15, TimeUnit.SECONDS);
        if (!finished) {
            process.destroyForcibly();
            throw new IOException("Timed out asking macOS to set the desktop picture.");
        }
        if (process.exitValue() != 0) {
            throw new IOException("macOS refused to set the desktop picture: " + output.trim());
        }
    }
}
