/*
 * Copyright (c) 2005-2007 Substance Kirill Grouchnikov. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 
 *  o Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer. 
 *     
 *  o Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution. 
 *     
 *  o Neither the name of Substance Kirill Grouchnikov nor the names of 
 *    its contributors may be used to endorse or promote products derived 
 *    from this software without specific prior written permission. 
 *     
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */
package org.jvnet.lafwidget.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.LinkedHashMap;
import java.util.Set;

import javax.swing.AbstractButton;
import javax.swing.Icon;

import org.jvnet.lafwidget.LafWidgetUtilities;
import org.jvnet.lafwidget.layout.TransitionLayout;
import org.jvnet.lafwidget.utils.FadeTracker.FadeKind;

/**
 * Utility class that implements the ghost effects.
 * 
 * @author Kirill Grouchnikov
 */
public class GhostPaintingUtils {
	/**
	 * Minimal starting opacity for icon ghosting. Change to a higher value for
	 * debugging / demoing purposes.
	 */
	public static float MIN_ICON_GHOSTING_ALPHA = 0.15f;

	/**
	 * Maximal starting opacity for icon ghosting. Change to a higher value for
	 * debugging / demoing purposes.
	 */
	public static float MAX_ICON_GHOSTING_ALPHA = 0.5f;
	
	/**
	 * Minimal starting opacity for press ghosting. Change to a higher value for
	 * debugging / demoing purposes.
	 */
	public static float MIN_PRESS_GHOSTING_ALPHA = 0.15f;
	
	/**
	 * Maximal starting opacity for press ghosting. Change to a higher value for
	 * debugging / demoing purposes.
	 */
	public static float MAX_PRESS_GHOSTING_ALPHA = 0.3f;

	/**
	 * Cache of ghost images. Used to speed up the rendering of the ghost
	 * effects.
	 */
	private static LinkedHashMap<String, BufferedImage> ghostCache = new LinkedHashMap<String, BufferedImage>() {
		protected boolean removeEldestEntry(
				java.util.Map.Entry<String, BufferedImage> eldest) {
			return this.size() > 50;
		}
	};

	/**
	 * Returns a scaled ghost image of the specified component.
	 * 
	 * @param comp
	 *            Component.
	 * @param scaleFactor
	 *            Scale factor.
	 * @return A scaled ghost image of the specified component.
	 */
	protected static synchronized BufferedImage getComponentGhostImage(
			Component comp, double scaleFactor) {
		FadeTracker ft = FadeTracker.getInstance();
		String key = ft.getCurrLoopId() + ":" + comp.hashCode() + ":"
				+ scaleFactor;

		BufferedImage result = ghostCache.get(key);
		if (result == null) {
			Rectangle bounds = comp.getBounds();

			double iWidth = bounds.width * scaleFactor;
			double iHeight = bounds.height * scaleFactor;
			result = LafWidgetUtilities.getBlankImage((int) iWidth,
					(int) iHeight);
			Graphics2D iGraphics = (Graphics2D) result.createGraphics();
			iGraphics.scale(scaleFactor, scaleFactor);
			comp.paint(iGraphics);
			iGraphics.dispose();

			ghostCache.put(key, result);
		}
		return result;
	}

	/**
	 * Paints ghost images on the specified component.
	 * 
	 * @param mainComponent
	 *            Component.
	 * @param g
	 *            Graphics context.
	 */
	public static void paintGhostImages(Component mainComponent, Graphics g) {
		if (!mainComponent.isShowing())
			return;
		if (!mainComponent.isVisible())
			return;

		Graphics2D graphics = (Graphics2D) g.create();

		Rectangle mainRect = mainComponent.getBounds();
		mainRect.setLocation(mainComponent.getLocationOnScreen());
		if (FadeConfigurationManager.getInstance().fadeAllowed(
				FadeKind.GHOSTING_BUTTON_PRESS, mainComponent)) {
			Set<Component> animComps = FadeTracker.getInstance()
					.getAllComponentsByFadeKind(FadeKind.GHOSTING_BUTTON_PRESS);

			for (Component comp : animComps) {
				if (comp == mainComponent)
					continue;

				if (!comp.isShowing())
					continue;
				if (!comp.isVisible())
					continue;

				Rectangle compRect = comp.getBounds();
				compRect.setLocation(comp.getLocationOnScreen());

				int dx = compRect.x - mainRect.x;
				int dy = compRect.y - mainRect.y;

				compRect.x -= compRect.width / 2;
				compRect.y -= compRect.height / 2;
				compRect.width *= 2;
				compRect.height *= 2;

				if (mainRect.intersects(compRect)) {
					float fade10 = FadeTracker.getInstance().getFade10(comp,
							null, FadeKind.GHOSTING_BUTTON_PRESS);
					// 0.0 --> 0.3
					// 10.0 --> 0.0
					double start = MAX_PRESS_GHOSTING_ALPHA - 0.0015
							* compRect.getWidth();
					float coef = Math.max((float) start,
							MIN_PRESS_GHOSTING_ALPHA);
					float opFactor = coef * (1.0f - fade10 / 10.0f);
					double iFactor = 1.0 + fade10 / 10.0;

					graphics.setComposite(TransitionLayout.getAlphaComposite(
							mainComponent, opFactor));
					//
					Rectangle bounds = comp.getBounds();
					//
					// double iWidth = bounds.width * iFactor;
					// double iHeight = bounds.height * iFactor;
					// BufferedImage iImage = SubstanceCoreUtilities
					// .getBlankImage((int) iWidth, (int) iHeight);
					// Graphics2D iGraphics = (Graphics2D)
					// iImage.createGraphics();
					// iGraphics.scale(iFactor, iFactor);
					// comp.paint(iGraphics);
					// iGraphics.dispose();
					// graphics.drawImage(iImage, dx, dy, null);

					BufferedImage ghost = getComponentGhostImage(comp, iFactor);
					dx -= (int) ((ghost.getWidth() - bounds.width) / 2);
					dy -= (int) ((ghost.getHeight() - bounds.height) / 2);
					graphics.drawImage(ghost, dx, dy, null);
				}
			}
		}

		if (FadeConfigurationManager.getInstance().fadeAllowed(
				FadeKind.GHOSTING_ICON_ROLLOVER, mainComponent)) {
			Set<Component> animComps = FadeTracker
					.getInstance()
					.getAllComponentsByFadeKind(FadeKind.GHOSTING_ICON_ROLLOVER);

			for (Component comp : animComps) {
				if (comp == mainComponent)
					continue;

				if (!comp.isShowing())
					continue;
				if (!comp.isVisible())
					continue;

				Rectangle compRect = comp.getBounds();
				compRect.setLocation(comp.getLocationOnScreen());

				int dx = compRect.x - mainRect.x;
				int dy = compRect.y - mainRect.y;

				compRect.x -= compRect.width / 2;
				compRect.y -= compRect.height / 2;
				compRect.width *= 2;
				compRect.height *= 2;

				if (mainRect.intersects(compRect)) {
					float fade10 = FadeTracker.getInstance().getFade10(comp,
							null, FadeKind.GHOSTING_ICON_ROLLOVER);
					// Rectangle bounds = comp.getBounds();
					Icon icon = null;
					Rectangle iconRect = null;
					if (comp instanceof AbstractButton) {
						AbstractButton button = (AbstractButton) comp;
						icon = LafWidgetUtilities.getIcon(button);
						iconRect = (Rectangle) button
								.getClientProperty("icon.bounds");
					}

					if ((icon != null) && (iconRect != null)) {
						double iFactor = 1.0 + fade10 / 10.0;
						double iWidth = icon.getIconWidth() * iFactor;
						double iHeight = icon.getIconHeight() * iFactor;
						BufferedImage iImage = LafWidgetUtilities
								.getBlankImage((int) iWidth, (int) iHeight);
						Graphics2D iGraphics = (Graphics2D) iImage
								.createGraphics();
						iGraphics.scale(iFactor, iFactor);
						icon.paintIcon(comp, iGraphics, 0, 0);
						iGraphics.dispose();

						// System.out.println(iconRect);

						// BufferedImage bImage = SubstanceCoreUtilities.blur(
						// iImage, 2);

						dx -= (int) ((iWidth - icon.getIconWidth()) / 2);
						dy -= (int) ((iHeight - icon.getIconHeight()) / 2);

						double start = MAX_ICON_GHOSTING_ALPHA
								- (MAX_ICON_GHOSTING_ALPHA - MIN_ICON_GHOSTING_ALPHA)
								* (iWidth - 16) / 48;
						float coef = Math.max((float) start,
								MIN_ICON_GHOSTING_ALPHA);
						float opFactor = coef * (1.0f - fade10 / 10.0f);
						graphics.setComposite(TransitionLayout
								.getAlphaComposite(mainComponent, opFactor));

						graphics.drawImage(iImage, dx + iconRect.x, dy
								+ iconRect.y, null);
					}
				}
			}
		}
		graphics.dispose();
	}

	/**
	 * Paints the ghost icon inside the bounds of the specified button.
	 * 
	 * @param graphics
	 *            Graphics context.
	 * @param b
	 *            Button.
	 * @param icon
	 *            Icon to paint.
	 */
	public static void paintGhostIcon(Graphics2D graphics, AbstractButton b,
			Icon icon) {
		paintGhostIcon(graphics, b, icon, (Rectangle) b
				.getClientProperty("icon.bounds"));
	}

	/**
	 * Paints the ghost icon inside the bounds of the specified button.
	 * 
	 * @param graphics
	 *            Graphics context.
	 * @param b
	 *            Button.
	 * @param iconRectangle
	 *            Rectangle of the button icon.
	 */
	public static void paintGhostIcon(Graphics2D graphics, AbstractButton b,
			Rectangle iconRectangle) {
		paintGhostIcon(graphics, b, LafWidgetUtilities.getIcon(b),
				iconRectangle);
	}

	/**
	 * Paints the ghost icon inside the bounds of the specified button.
	 * 
	 * @param graphics
	 *            Graphics context.
	 * @param b
	 *            Button.
	 * @param icon
	 *            Icon to paint.
	 * @param iconRectangle
	 *            Rectangle of the button icon.
	 */
	public static void paintGhostIcon(Graphics2D graphics, AbstractButton b,
			Icon icon, Rectangle iconRectangle) {
		// System.out.println(b.getText() + ":" + icon + ":" + iconRectangle);
		if (!FadeConfigurationManager.getInstance().fadeAllowed(
				FadeKind.GHOSTING_ICON_ROLLOVER, b)) {
			return;
		}

		if (FadeTracker.getInstance().isTracked(b, null,
				FadeKind.GHOSTING_ICON_ROLLOVER, true)) {
			float fade10 = FadeTracker.getInstance().getFade10(b,
					FadeKind.GHOSTING_ICON_ROLLOVER);
			// System.out.println(" --> " + fade10);
			double start = 0.5 - 0.35 * (icon.getIconWidth() - 16) / 48;
			float coef = Math.max((float) start, 0.15f);
			float opFactor = coef * (1.0f - fade10 / 10.0f);
			graphics.setComposite(TransitionLayout.getAlphaComposite(b,
					opFactor));
			// System.out.println(opFactor);

			// Rectangle iconRect = (Rectangle)
			// b.getClientProperty("icon.bounds");

			if ((icon != null) && (iconRectangle != null)) {
				double iFactor = 1.0 + fade10 / 10.0;
				double iWidth = icon.getIconWidth() * iFactor;
				double iHeight = icon.getIconHeight() * iFactor;
				BufferedImage iImage = LafWidgetUtilities.getBlankImage(
						(int) iWidth, (int) iHeight);
				Graphics2D iGraphics = (Graphics2D) iImage.createGraphics();
				iGraphics.scale(iFactor, iFactor);
				icon.paintIcon(b, iGraphics, 0, 0);
				iGraphics.dispose();
				int dx = (int) ((iWidth - icon.getIconWidth()) / 2);
				int dy = (int) ((iHeight - icon.getIconHeight()) / 2);
				graphics.drawImage(iImage, iconRectangle.x - dx,
						iconRectangle.y - dy, null);
			}
		}
	}
}
