/*$cb
 *    This file is a part of libopenmhp.
 *
 *    Copyright (C) 2005 Mikko Novaro <miknov@gmail.com>
 *
 *    See main header file (libopenmhp/openmhp.h) for licensing and
 *    contact information.
 $ce*/

package libopenmhp;

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import libopenmhp.message.ImageUpdate;

/** Class for capturing xlet images from OpenMHP and passing them to client. */
public class Grabber {
    
    public static Grabber instance;
    public static final int LAYER_COUNT = 2;
    public static final int GRAPHICS_LAYER_INDEX = 0;
    public static final int BACKGROUND_LAYER_INDEX = 1;

    static {
    	System.loadLibrary("grabber");
	initSharing();
    }
    
    private static int[][] pixels = new int[LAYER_COUNT][720*576];

    private static BufferedImage bi[] = new BufferedImage[LAYER_COUNT];
    private static Graphics g[] = new Graphics[LAYER_COUNT];

    public static Graphics getGraphics(int layerIndex) {
        if (bi[layerIndex] == null) {
    	    bi[layerIndex] = new BufferedImage(720, //comp.getSize().width,
					       576, //comp.getSize().height,
					       // BufferedImage.TYPE_BYTE_INDEXED);
					       BufferedImage.TYPE_INT_ARGB);
    	    // Choice of BufferedImage type didn't affect getRGB speed
    	    // (which isn't anyway used anymore..)
    	    g[layerIndex] = bi[layerIndex].createGraphics();
    	    pixels[layerIndex] = ((DataBufferInt)(bi[layerIndex].getRaster().getDataBuffer())).getData();
    	}
    	else {
    	    for (int i=0; i<720*576; i++) pixels[layerIndex][i] = 0;
    	}
        return g[layerIndex]; // bi.createGraphics();
    }
	

    /** Shares the graphics painted into the graphics object acquired
     * by the previous call of Grabber.getGraphics. */
    public static void share(int layerIndex) {
    	// DEBUG: System.out.print("java...");
    	// DEBUG: long t1 = System.currentTimeMillis();
    	/*
    	for (int y=0; y<576; y++) {
    	    for (int x=0; x<720; x++) {
    		pixels[y*720+x] = bi.getRGB(x,y);
    		// if (x==20&&y==20) System.out.println("java: (20,20)="+pixels[y*720+x]);
    	    }
    	}
    	*/
    	// bi.getRGB(0,0, 720, 576, pixels, 0, 720);
    	// DEBUG: long t2 = System.currentTimeMillis();
    	// DEBUG: System.out.println("...java: " + (t2-t1));
    	shareSnapshot(pixels[layerIndex], layerIndex);
	InterfaceServer.getInstance().sendMessage(new ImageUpdate(layerIndex));
    }


    public native static void shareSnapshot(int[] snapshot, int layerIndex);
    public native static boolean initSharing();
    public native static void endSharing();

}
