package com.aimmac23.node;

import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBufferInt;
import java.util.Arrays;

import com.aimmac23.node.jna.EncoderInterface;
import com.aimmac23.node.jna.JnaLibraryLoader;
import com.sun.jna.Pointer;

public class RobotScreenshotSource implements ScreenshotSource {

	private Robot robot;

	public RobotScreenshotSource() throws Exception {
		robot = new Robot();
	}
	
	@Override
	public int applyScreenshot(Pointer encoderContext) {
		BufferedImage image = robot.createScreenCapture(getScreenSize());

		int[] screenshotData = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
		
		EncoderInterface encoder = JnaLibraryLoader.getEncoder();

		return encoder.convert_frame(encoderContext, screenshotData);
	}

	@Override
	public int getWidth() {
		return getScreenSize().width;
	}

	@Override
	public int getHeight() {
		return getScreenSize().height;
	}

	protected Rectangle getScreenSize() {
		//XXX: This probably won't work with multiple monitors
		return GraphicsEnvironment.getLocalGraphicsEnvironment().
				getDefaultScreenDevice().getDefaultConfiguration().getBounds();
		
	}

	@Override
	public void doStartupSanityChecks() {
		// test to make assert that the bit depth is 32 bit
		
		ColorModel colorModel = GraphicsEnvironment.getLocalGraphicsEnvironment().
		getDefaultScreenDevice().getDefaultConfiguration().getColorModel();
		
		int[] bitAllocations = colorModel.getComponentSize();
		
		int bitDepth = 0;
		
		for(int pixelBitSize : bitAllocations) {
			bitDepth += pixelBitSize; 
		}
		
		if(bitDepth != 32) {
			throw new IllegalStateException("Could not start - display bit depth is not 32-bit");
		}
	}
}

@@ -1361,17 +1361,28 @@
 pth 
-is 32 bit
+has 8 bits per pixel
 %0A%09%09%0A
@@ -1596,105 +1596,109 @@
 %09%0A%09%09
-int bitDepth = 0;%0A%09%09%0A%09%09for(int pixelBitSize : bitAllocations) %7B%0A%09%09%09bitDepth += pixelBitSize; %0A%09%09%7D
+// don't count alpha bits%0A%09%09int bitDepth = bitAllocations%5B0%5D + bitAllocations%5B1%5D + bitAllocations%5B2%5D;
 %0A%09%09%0A
@@ -1714,18 +1714,18 @@
 epth != 
-3
 2
+4
 ) %7B%0A%09%09%09t
@@ -1760,58 +1760,172 @@
 on(%22
-Could not start - display bit depth is not 32-bit%22
+Display colour depth incorrect (should be 8 bits of red, blue and green). Currently: %22 %0A%09%09%09%09%09+ bitAllocations%5B0%5D + %22-%22 + bitAllocations%5B1%5D + %22-%22 + bitAllocations%5B2%5D
 );%0A%09

Fix bit depth detection logic, and error message