/**
 *
 */
package workers;

import model.SOMImage;

import java.io.IOException;
import java.nio.file.Files;

import static java.nio.file.StandardCopyOption.ATOMIC_MOVE;

/**
 * @author Simon Gehrig
 */
class CaptureWorker {

    /**
     * Captures an image and returns it
     *
     * @return the SOMImage captured or null in case of failure
     */
    public static SOMImage now() {
        SOMImage image = new SOMImage();
        try {
            // get a process taking the image
            ProcessBuilder builder = new ProcessBuilder(
                    "gphoto2",
                    "--capture-image-and-download",
                    "--filename=" + image.getTmp().toString());
            builder.redirectErrorStream(true);

            // launch capture!
            Process process = builder.start();

            // wait for the process to end
            if (process.waitFor() == 0) {

                // MOVE & RENAME THE IMAGE
                Files.move(image.getTmp().toPath(), image.getSrc().toPath(), ATOMIC_MOVE);
            } else {
                System.out.println("Capture Process failed");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return image;
    }
}
