package jxcapture.image.win;

import com.teamdev.jxcapture.CompressionQuality;
import com.teamdev.jxcapture.ImageCapture;
import com.teamdev.jxcapture.image.ImageFormat;
import com.teamdev.jxcapture.video.WindowSource;
import com.teamdev.jxdesktop.WindowManager;
import com.teamdev.jxdesktop.ui.Window;

import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CaptureWindow {

    private static final Logger logger = LoggerFactory.getLogger(CaptureWindow.class);

    /*
     * Take screenshot of specific window based on title.
     */
    public void getWindow(String title) throws Exception {
        WindowManager windowManager = WindowManager.getInstance();
        Window window = (Window) windowManager.findWindow(title);

        if (window == null) {
            logger.error("Window with title \"{}\" not found ");
            throw new Exception("Window not found");
        }

        logger.debug("Capturing image of {}", title);

        ImageCapture imageCapture = ImageCapture.create(new WindowSource(window));
        imageCapture.setCaptureArea(new Rectangle(window.getSize()));
        imageCapture.setCaptureTransparentWindows(true);

        imageCapture.takeSnapshot().save(new File("d:\\capture\\" + title + ".jpg"), ImageFormat.JPEG, CompressionQuality.BEST);

        imageCapture.release();
    }

    /*
     * Take a screen shot of all visible windows
     */
    public void getAllWindows() throws Exception {
        WindowManager windowManager = WindowManager.getInstance();
        int i = 0;

        List<Window> windows = windowManager.getVisibleWindows();

        // print the list of all visible windows.

        for (Window window : windows) {
            i++;
            logger.debug("{}. {}", i, window.getTitle());
        }

        i = 0;
        ImageCapture imageCapture;
        for (Window window : windowManager.getVisibleWindows()) {
            i++;
            if(window==null) continue;
            imageCapture = ImageCapture.create(new WindowSource(window));

            // Do we really need to resize when we require the whole window content?
            // imageCapture.setCaptureArea(new Rectangle(window.getSize()));

            // Get the name and normalize it for file name
            try {
                String name = normalizeName(window.getTitle(), 10);
                imageCapture.takeSnapshot().save(new File("d:\\capture\\all\\" + i + "_" + name + ".jpg"), ImageFormat.JPEG,
                        CompressionQuality.BEST);
            } catch (Exception e) {
                logger.error("capture failed for {}", window.getTitle(), e);
            } finally {
                if (imageCapture != null)
                    imageCapture.release();
            }

        }

    }

    /*
     * Take screenshot of whole desktop.
     */
    public void getDesktop() throws Exception {

        ImageCapture imageCapture = ImageCapture.create();
        imageCapture.takeSnapshot().save(new File("d:\\capture\\Desktop.png"), ImageFormat.JPEG, CompressionQuality.BEST);
        imageCapture.release();

    }

    public String normalizeName(String windowName, int length) {

        String firstNorm = windowName.replaceAll("[:?\\/,*]", "");
        int endx = firstNorm.length() > length ? length - 1 : firstNorm.length() - 1;
        return firstNorm == null ? " " : firstNorm.substring(0, endx);
    }


    public static void main( String[] args ) throws Exception
    {
        CaptureWindow cw = new CaptureWindow();
        cw.getDesktop();
        cw.getAllWindows();
        cw.getWindow("Untitled - Notepad");
        cw.getWindow("Task Manager");


    }

}

