package edu.unl.consystlab.gui;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.ImageObserver;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;

import edu.unl.consystlab.util.Debug;

public class ImageCombine {
    private ImageCombine() {

        // no instantation please
    }

    public static Image combine(ImageObserver o, Image left, Image right) {

        int h = left.getHeight(o);
        int w = left.getWidth(o);

        PixelGrabber pgl = new PixelGrabber(left, 0, 0, -1, -1, true);
        PixelGrabber pgr = new PixelGrabber(right, 0, 0, -1, -1, true);

        boolean res = false;

        try {
            res = pgl.grabPixels();
            if(res)
                res = pgr.grabPixels();
        }
        catch (Exception e) {
            Debug.debug("Combine.combine(): grabPixels() failed: " + e);
        }
        Debug.debug("Combine.combine(): grabPixels(): res=" + res);

        int[] pix_l = (int[]) pgl.getPixels();
        int[] pix_r = (int[]) pgr.getPixels();
        int[] pix = new int[pix_l.length];

        int a = 255 << 24;
        int r = 255 << 16;
        int g = 255 << 8;
        int b = 255 << 0;
        int fl = a | 0 | g | b;
        int fr = a | r | 0 | 0;

        Debug.debug("ImageCombine.combine(): # pixels=" + pix.length);
        for (int i = 0; i < pix.length; i++) {

            pix[i] = (pix_l[i] & fl) | (pix_r[i] & fr);
            //pix[i] = pix_r[i];
        }
        MemoryImageSource mis = new MemoryImageSource(w, h, pix, 0, w);
        Image image = Toolkit.getDefaultToolkit().createImage(mis);
        return image;
    }

}