package com.horstmann.labrat;

import java.awt.Frame;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

import javax.imageio.ImageIO;

public class SnapFrame
{
   public static void main(String[] args) throws Exception
   {
      List<Frame> oldFrames = Arrays.asList(Frame.getFrames());
      Class cl = Class.forName(args[0]);
      Method m = cl.getMethod("main", String[].class);
      m.invoke(null, (Object) new String[] {});

      // find first new frame
      Frame[] frames = Frame.getFrames();
      int i = 0;
      while (i < frames.length && oldFrames.contains(frames[i]))
         i++;
      if (i == frames.length) return;
      Frame frame = frames[i];

      Robot robot = new Robot();
      robot.delay(1000);
      robot.waitForIdle();
      BufferedImage image = robot.createScreenCapture(frame.getBounds());

      // TODO: full-screen option
      String output = args[1];
      String extension = output.substring(output.lastIndexOf('.') + 1);
      ImageIO.write(image, extension, new File(output));
      System.exit(0);
   }
}
