/*
 * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.toolbox.rebop;

/**
 * Title:        ImageUtils
 * Description:  Utility functions to manipulate Images
 * @author Gavin Doughtie
 */

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.image.ImageObserver;
import java.awt.image.PixelGrabber;
import java.awt.image.MemoryImageSource;

public class ImageUtils {
    public static final String versionId = "$Id: //core-platform/dev/src/com/arsdigita/toolbox/rebop/ImageUtils.java#6 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";

    public ImageUtils() {
    }

    public static Image createTiledImage(Image tile, int w, int h, Component c) {
        Image i = c.createImage(w, h);
        if (null == i) {
            System.out.println("Null image for: " + w + ", " + h);
            return null;
        }

        return createTiledImage(tile, i, w, h, c);
    }

    public static Image createTiledImage(
                                         Image tile,
                                         Image output,
                                         int w,
                                         int h,
                                         ImageObserver c) {
        if (null == tile || null == output) {
            System.out.println("tile: " + tile + " output: " + output);
            return null;
        }

        int imageW = tile.getWidth(c);
        int imageH = tile.getHeight(c);
        Graphics fillG = output.getGraphics();
        if (null == fillG) {
            return null;
        }

        drawTiledImage(
                       fillG,
                       0,
                       0,
                       new Rectangle(0, 0, imageW, imageH),
                       tile,
                       w,
                       h,
                       c);
        fillG.dispose();
        return output;
    }

    public static void drawTiledImage(
                                      Graphics g,
                                      int startX,
                                      int startY,
                                      Rectangle sourceRect,
                                      Image sourceImage,
                                      int width,
                                      int height,
                                      ImageObserver obs) {
        int columns = width <= sourceRect.width ? 1 : width / sourceRect.width + 1;
        int rows = height <= sourceRect.height ? 1 : height / sourceRect.height + 1;
        int currentX = startX;
        int currentY = startY;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                g.drawImage(sourceImage,
                            currentX,
                            currentY,
                            currentX + sourceRect.width,
                            currentY + sourceRect.height,
                            sourceRect.x,
                            sourceRect.y,
                            sourceRect.x + sourceRect.width,
                            sourceRect.y + sourceRect.height,
                            Color.white,
                            obs);

                currentX += sourceRect.width;
            }
            currentY += sourceRect.height;
            currentX = startX;
        }
    }

    public static void alphaDraw
        (
         Graphics g,
         Component comp,
         int x,
         int y,
         int[] backgroundPixels,
         int bgWidth,
         int bgHeight,
         int spriteW,
         int spriteH,
         Image spriteImage,
         Image alphaImage,
         int pct
         ) {
        try {
            int[] spPixels = new int[spriteW * spriteH];
            int[] alphaPixels = new int[spPixels.length];
            int[] compositePixels = new int[spPixels.length];
            PixelGrabber pg = new PixelGrabber(
                                               spriteImage,
                                               0,
                                               0,
                                               spriteW,
                                               spriteH,
                                               spPixels,
                                               0,
                                               spriteW);
            pg.grabPixels();

            pg = new PixelGrabber(
                                  alphaImage,
                                  0,
                                  0,
                                  spriteW,
                                  spriteH,
                                  alphaPixels,
                                  0,
                                  spriteW);
            pg.grabPixels();

            // Pack the alpha channel into the sprite's pixels
            for (int i = 0; i < spPixels.length; i++) {
                // kill any alpha we might have
                spPixels[i] &= 0xFFFFFF;
                // Replace the alpha with the blue value of the alpha image
                if (null != alphaPixels) {
                    spPixels[i] |= alphaPixels[i] << 24;
                }
            }

            MemoryImageSource source = new MemoryImageSource(
                                                             spriteW, spriteH, compositePixels, 0, spriteW);
            source.setAnimated(true);
            Image compositedImage = comp.createImage(source);

            int wDiff = bgWidth - (x + spriteW);
            if (wDiff < 0) {
                spriteW += wDiff;
            }
            int hDiff = bgHeight - (y + spriteH);
            if (hDiff < 0) {
                spriteH += hDiff;
            }

            ImageUtils.alphaComposite(
                                      x,
                                      y,
                                      spriteW,
                                      spriteH,
                                      bgWidth,
                                      bgHeight,
                                      spPixels,
                                      backgroundPixels,
                                      compositePixels,
                                      pct,
                                      true,
                                      false);

            source.newPixels(0, 0, spriteW, spriteH);

            g.drawImage(compositedImage, x, y, comp);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * @author Gavin Doughtie
     * @param x top-left x-coordinate in background image that sprite overlaps
     * @param y top-left y-coordinate in background image that sprite overlaps
     * @param spWidth width of sprite in pixels
     * @param spHeight height of sprite in pixels
     * @param bgWidth width of background image in pixels
     * @param bgHeight height of background image in pixels
     * @param spritePixels pixels representing the sprite,
     * including an 8-bit Alpha channel
     * @param backgroundPixels pixels representing the background
     * over which the sprite will be composited
     * @param compositePixels pixels that will receive the composite value
     * @param pct degree of intensity for the blend, from 0 to 255
     * @param useAlpha if false, percentage blend only,
     * ignoring alpha channel in sprite
     * Alpha-composites a sprite over a background image
     */
    public static void alphaComposite
        (
         int x,
         int y,
         int spWidth,
         int spHeight,
         int bgWidth,
         int bgHeight,
         int[] spritePixels,
         int[] backgroundPixels,
         int[] compositePixels,
         int pct,
         boolean useAlpha,
         boolean updateBackground
         ) {
        int a = 0;
        int outputIndex = 0;
        int spixelvalue = 0;
        int pixelvalue = 0;

        for (int j = y; j < (y + spHeight); j++) {
            for (int i = x; i < (x + spWidth); i++) {
                int pixelIndex = (j * bgWidth) + i;

                spixelvalue=spritePixels[outputIndex];
                pixelvalue=backgroundPixels[pixelIndex];

                // unpack alpha
                if (useAlpha) {
                    a = spixelvalue >>> 24;
                    a = a * pct >> 8;
                } else {
                    a = pct;
                }

                int dstrb = pixelvalue & 0xFF00FF;
                int dstg = pixelvalue & 0xFF00;

                int srcrb = spixelvalue & 0xFF00FF;
                int srcg = spixelvalue & 0xFF00;

                int drb = dstrb - srcrb;
                int dg = dstg - srcg;

                drb *= a;
                dg *= a;
                drb >>>= 8;
                dg >>>= 8;

                int rb = (dstrb - drb) & 0xFF00FF;
                int g  = (dstg - dg) & 0xFF00;

                compositePixels[outputIndex] = 0xFF000000 | rb | g;
                if (updateBackground) {
                    backgroundPixels[pixelIndex] =
                        compositePixels[outputIndex];
                }
                outputIndex++;
            }
        }
    }
}
