/*
 * 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.Component;
import java.awt.Rectangle;
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.LafWidgetRepository;
import org.jvnet.lafwidget.LafWidgetUtilities;
import org.jvnet.lafwidget.utils.FadeTracker.FadeKind;

/**
 * Listener for the "ghisting image" effects on buttons.
 * 
 * @author Kirill Grouchnikov
 * @see SubstanceLookAndFeel#GHOSTING_BUTTON_PRESS
 * @see SubstanceLookAndFeel#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 FadeTracker.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.
	 * @param callback
	 *            Optional application callback.
	 */
	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.
	 * @param toRepaintParent
	 *            If <code>true</code>, the component parent will be
	 *            repainted at every animation cycle. If <code>false</code>,
	 *            the component itself will be repainted at every animation
	 *            cycle.
	 */
	protected void trackModelChange(FadeKind fadeKind, boolean newState) {
		if (LafWidgetRepository.getRepository().getFadeIgnoreManager()
				.toIgnoreAnimations(this.comp))
			return;
		try {
			if (this.prevStateMap.containsKey(fadeKind)) {
				boolean prevState = this.prevStateMap.get(fadeKind);
				if (!prevState && newState) {
					// int compIndex = -1;
					// for (int i = 0; i < this.comp.getParent()
					// .getComponentCount(); i++) {
					// if (this.comp.getParent().getComponent(i) == this.comp) {
					// compIndex = i;
					// break;
					// }
					// }
					// if (compIndex < 0)
					// return;
					FadeTracker.getInstance().trackFadeIn(fadeKind, this.comp,
							null, false, new FadeTracker.FadeTrackerCallback() {
								protected void repaintParent(int x, int y,
										int width, int height) {
									if (comp == null)
										return;

									if (!comp.isShowing())
										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;
									root
											.repaint(
													compRect.x
															- root
																	.getLocationOnScreen().x,
													compRect.y
															- root
																	.getLocationOnScreen().y,
													compRect.width,
													compRect.height);
									//
									// if (comp.getParent() == null)
									// return;
									// comp.getParent().repaint(x, y, width,
									// height);
								}

								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.repaintParent(bounds.x - dx, bounds.y
											- dy, (int) iWidth, (int) iHeight);
								}

								public void fadePerformed(FadeKind fadeKind,
										float fadeCycle10) {
									Rectangle bounds = comp.getBounds();
									double iFactor = 1.0 + fadeCycle10 / 10.0;
									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.repaintParent(bounds.x - dx, bounds.y
											- dy, (int) iWidth, (int) iHeight);
								}
							}, 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);
	}
}
