/**
 * Authors : quentin.vaney@gmail.com;xavier.frelechoz@gmail.com
 * Version : V1
 */

package LaTexScreenshooter;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Toolkit;

public class WaylandScreenshooter {

    // Opens a URL in the default browser
    private static void openWebPage(String url) throws IOException {
        System.out.println("Opening web page: " + url);
        Desktop.getDesktop().browse(URI.create(url));
    }

    // Captures the screen and saves the image
    private static void captureScreenshot(String fileName, String path, String s) throws IOException {
        System.out.println("Capturing screenshot...");
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        String command = "gnome-screenshot -w -f " + path + fileName + ".png";
        try {
            Process process = Runtime.getRuntime().exec(command);
            process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Screenshot saved at location: " + path + fileName + ".png");
    }

    // Closes the web page
    private static void closeWebPage() {
        System.out.println("Closing web page...");
        try {
            Runtime.getRuntime().exec("ydotool key ctrl+w");
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Web page closed.");
    }

    // Captures the screen after opening a web page
    public static void captureScreenshot(String url, int width, int height, String fileName, String path) {
        try {
            openWebPage(url);
            Thread.sleep(4000); // Wait for 4 seconds for the page to load
            captureScreenshot(fileName, path, path);
            closeWebPage();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void resizeImage(int scaledWidth, int scaledHeight, String fileName) throws IOException {
        // Read the input image from the specified path
        File inputFile = new File(System.getProperty("user.dir") + "/" + fileName + ".png");
        BufferedImage inputImage = ImageIO.read(inputFile);

        // Create a BufferedImage with the new dimensions
        BufferedImage outputImage = new BufferedImage(scaledWidth, scaledHeight, inputImage.getType());

        // Resize the image
        Graphics2D graphics2D = outputImage.createGraphics();
        graphics2D.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
        graphics2D.dispose();

        // Write the resized image to the specified path
        ImageIO.write(outputImage, "png", new File(fileName + ".png"));
    }
}
