/*
 * 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.animation.effects;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

import javax.swing.ButtonModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.jvnet.lafwidget.LafWidgetUtilities;
import org.jvnet.lafwidget.animation.*;

/**
 * Listener for the "ghosting image" effects on buttons.
 * 
 * @author Kirill Grouchnikov
 * @see FadeKind#GHOSTING_BUTTON_PRESS
 * @see FadeKind#GHOSTING_ICON_ROLLOVER
 */
public class GhostingListener {
	/**
	 * Listener on the model changes.
	 */
	protected ChangeListener modelListener;

	/**
	 * The associated component.
	 */
	protected Component comp;

	/**
	 * The associated model.
	 */
	protected ButtonModel buttonModel;

	/**
	 * Key - {@link FadeKind}, value - {@link Boolean}
	 */
	protected Map<FadeKind, Boolean> prevStateMap;

	/**
	 * Creates a new listener on model changes that can cause fade animation
	 * transitions.
	 * 
	 * @param comp
	 *            Component.
	 * @param buttonModel
	 *            Model for the component.
	 */
	public GhostingListener(Component comp, ButtonModel buttonModel) {
		this.comp = comp;
		this.buttonModel = buttonModel;

		this.prevStateMap = new HashMap<FadeKind, Boolean>();
		this.prevStateMap.put(FadeKind.GHOSTING_ICON_ROLLOVER, buttonModel
				.isRollover());
		this.prevStateMap.put(FadeKind.GHOSTING_BUTTON_PRESS, buttonModel
				.isPressed());
	}

	/**
	 * Tracks a single change to the model.
	 * 
	 * @param fadeKind
	 *            Fade animation kind.
	 * @param newState
	 *            New value of the relevant attribute of the model.
	 */
	protected void trackModelChange(FadeKind fadeKind, boolean newState) {
		if (LafWidgetUtilities.toIgnoreAnimations(this.comp))
			return;
		try {
			if (this.prevStateMap.containsKey(fadeKind)) {
				boolean prevState = this.prevStateMap.get(fadeKind);
				if (!prevState && newState) {
					FadeTracker.getInstance().trackFadeIn(fadeKind, this.comp,
							null, false, new UIThreadFadeTrackerAdapter() {
								private boolean wasShowing = true;

								protected void repaintTopLevelWindows(
										float fadeCycle) {
									if (comp == null)
										return;

									boolean isShowing = comp.isShowing();
									if (isShowing) {
										Window compWindow = SwingUtilities
												.getWindowAncestor(comp);
										if (!compWindow.isDisplayable()
												|| !compWindow.isShowing()
												|| !compWindow.isVisible()) {
											isShowing = false;
										}
									}

									if (!isShowing) {
										if (wasShowing) {
											// need to repaint all other windows
											// once - otherwise we will see
											// painting artifacts from
											// a pressed button that was made
											// invisible
											for (Window w : Window.getWindows()) {
												if (w.isDisplayable()
														&& w.isVisible()
														&& w.isShowing()) {
													w.repaint();
												}
											}
										}
										wasShowing = false;
										return;
									}
									Component root = SwingUtilities
											.getRoot(comp);
									Rectangle compRect = comp.getBounds();
									compRect.setLocation(comp
											.getLocationOnScreen());
									compRect.x -= compRect.width / 2;
									compRect.y -= compRect.height / 2;
									compRect.width *= 2;
									compRect.height *= 2;
									int rootRepaintX = compRect.x
											- root.getLocationOnScreen().x;
									int rootRepaintY = compRect.y
											- root.getLocationOnScreen().y;
									// String rootTitle = (root instanceof Frame
									// ) ? ((Frame) root)
									// .getTitle()
									// : (root instanceof Dialog) ? ((Dialog)
									// root)
									// .getTitle()
									// : null;
									// System.out.println("Repainting "
									// + fadeCycle10 + ":" + rootTitle
									// + "[self] at " + rootRepaintX + ":"
									// + rootRepaintY + ":"
									// + compRect.width + ":"
									// + compRect.height);

									root.repaint(rootRepaintX, rootRepaintY,
											compRect.width, compRect.height);

									// fix for issue 363 on Substance - repaint
									// all top-level windows that intersect
									// with this rectangle
									for (Window w : Window.getWindows()) {
										if (w == root)
											continue;
										String title = (w instanceof Frame) ? ((Frame) w)
												.getTitle()
												: (w instanceof Dialog) ? ((Dialog) w)
														.getTitle()
														: null;
										// System.out.println(title + ":"
										// + w.isDisplayable() + ":"
										// + w.isVisible());
										if (w.isDisplayable() && w.isVisible()
												&& w.isShowing()) {
											// System.out.println(w.getBounds()
											// .intersects(compRect)
											// + ":"
											// + w.getBounds()
											// + ":"
											// + compRect);
											if (w.getBounds().intersects(
													compRect)) {
												int winRepaintX = compRect.x
														- w
																.getLocationOnScreen().x;
												int winRepaintY = compRect.y
														- w
																.getLocationOnScreen().y;
												// System.out
												// .println("Repainting "
												// + fadeCycle
												// + ":"
												// + title
												// + " at "
												// + winRepaintX
												// + ":"
												// + winRepaintY
												// + ":"
												// + compRect.width
												// + ":"
												// + compRect.height);
												w.repaint(winRepaintX,
														winRepaintY,
														compRect.width,
														compRect.height);
											}
										}
									}
								}

								@Override
								public void fadeEnded(FadeKind fadeKind) {
									// Rectangle bounds = comp.getBounds();
									// double iWidth = bounds.width * 2;
									// double iHeight = bounds.height * 2;
									// int dx = (int) ((iWidth - bounds.width) /
									// 2);
									// int dy = (int) ((iHeight - bounds.height)
									// / 2);
									this.repaintTopLevelWindows(1.0f);
								}

								@Override
								public void fadePerformed(FadeKind fadeKind,
										float fadeCycle) {
									// Rectangle bounds = comp.getBounds();
									// double iFactor = 1.0 + fadeCycle
									// ;
									// double iWidth = bounds.width * iFactor;
									// double iHeight = bounds.height * iFactor;
									// int dx = (int) ((iWidth - bounds.width) /
									// 2);
									// int dy = (int) ((iHeight - bounds.height)
									// / 2);
									this.repaintTopLevelWindows(fadeCycle);
								}
							}, LafWidgetUtilities.getAnimationKind(comp));
				}
			}
		} finally {
			this.prevStateMap.put(fadeKind, Boolean.valueOf(newState));
		}
	}

	/**
	 * Registers listeners on the relevant model changes.
	 */
	public void registerListeners() {
		this.modelListener = new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				if (FadeConfigurationManager.getInstance().fadeAllowed(
						FadeKind.GHOSTING_ICON_ROLLOVER, comp)) {
					trackModelChange(FadeKind.GHOSTING_ICON_ROLLOVER,
							buttonModel.isRollover());
				}
				if (FadeConfigurationManager.getInstance().fadeAllowed(
						FadeKind.GHOSTING_BUTTON_PRESS, comp)) {
					trackModelChange(FadeKind.GHOSTING_BUTTON_PRESS,
							buttonModel.isPressed());
				}
			}
		};
		this.buttonModel.addChangeListener(this.modelListener);
	}

	/**
	 * Unregisters all listeners on model changes.
	 */
	public void unregisterListeners() {
		this.buttonModel.removeChangeListener(this.modelListener);
	}
}
