/*
  Copyright (c) 2003-2006, Robert F. Beeger (robert at beeger dot net)
  All rights reserved.

  Redistribution and use in source and binary forms, with or without modification,
  are permitted provided that the following conditions are met:

      * Redistributions of source code must retain the above copyright notice, this list
        of conditions and the following disclaimer.
      * 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.
      * Neither the name of 'Robert F. Beeger' nor the names of his 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.

  Visit http://squareness.beeger.net/ for new releases of Squareness Look And Feel and other
  skins from the Squareness series.
*/
package net.beeger.squareness.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JComponent;
import javax.swing.JToolBar;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.plaf.UIResource;

import net.beeger.squareness.SquarenessConstants;
import net.beeger.squareness.SquarenessLookAndFeel;

/**
 * Utility class used by UI delegates for all kinds of buttons.
 */
public class SquarenessButtonPainter
{

  /**
   * Paint a button.
   *
   * @param graphics The graphics object to be used for painting.
   * @param button The button to paint
   */
  public static void paintButton (Graphics graphics, AbstractButton button)
  {
    Color oldColor = graphics.getColor();

    ButtonModel model = button.getModel();

    Insets buttonInsets = getInnermostOpaqueBorderInsets(button.getBorder(), button);
    if (buttonInsets == null)
    {
      buttonInsets = new Insets(0, 0, 0, 0);
    }

    boolean isRollover = ((Boolean) button.getClientProperty(SquarenessConstants.ROLLOVER_CLENT_PROPERTY_KEY)).booleanValue();

    if (buttonInsets.top == 0 && buttonInsets.bottom == 0 && buttonInsets.right == 0 && buttonInsets.left == 0
        && button.getBackground() instanceof UIResource)
    {
      paintBorderlessButton(graphics, button);
    }
    else if (button.isEnabled()
             && (isRollover
                 || model.isArmed() && model.isPressed()
                 || button.hasFocus()
                 || button.isSelected()))
    {
      boolean paintShadow = model.isArmed() && model.isPressed() || button.isSelected() && !isRollover;
      paintNormalButton(graphics, buttonInsets, button, paintShadow);

    }
    else if (button.getParent() != null
             && button.getParent() instanceof JToolBar
             && ((JToolBar) button.getParent()).getClientProperty("JToolBar.isRollover") != null
             && ((Boolean) ((JToolBar) button.getParent()).getClientProperty("JToolBar.isRollover")).booleanValue())
    {
      paintBorderlessButton(graphics, button);
    }

    graphics.setColor(oldColor);
  }

  /**
   * Paint a normal button that has a border.
   *
   * @param graphics The graphics object used for painting
   * @param buttonInsets The insets of the visible part of the border of the button.
   * @param button The button to paint
   * @param paintShadow Shall the shadow for pressed buttons be painted.
   */
  private static void paintNormalButton (Graphics graphics, Insets buttonInsets, AbstractButton button,
                                         boolean paintShadow)
  {
    graphics.setColor(SquarenessLookAndFeel.getCurrentSquarenessTheme().getSelectedControlBackgroundColor());
    graphics.fillRect(buttonInsets.left, buttonInsets.top,
                      button.getWidth() - buttonInsets.right,
                      button.getHeight() - buttonInsets.bottom);

    if (paintShadow)
    {
      graphics.setColor(SquarenessLookAndFeel.getCurrentSquarenessTheme().getSelectedControlBackgroundShadowColor());
      graphics.fillRect(buttonInsets.left, buttonInsets.top, 2, button.getHeight() - buttonInsets.bottom);
      graphics.fillRect(buttonInsets.left, buttonInsets.top, button.getWidth() - buttonInsets.right, 2);
    }
  }

  /**
   * Paint a button that doesn't have a border. Such buttons take the background color of their parents as their
   * background color. Only when they are pressed or in rollover mode - in which case they have a border -
   * they have the same color like buttons with borders in the same state.
   *
   * @param graphics The graphics object used for painting.
   * @param button The button to paint.
   */
  private static void paintBorderlessButton (Graphics graphics, AbstractButton button)
  {
    graphics.setColor(button.getParent() != null
                      ? button.getParent().getBackground() 
                      : SquarenessLookAndFeel.getCurrentSquarenessTheme().getWindowBackgroundColor());
    graphics.fillRect(0, 0, button.getWidth(), button.getHeight());
  }

  /**
   * Return the insets of the border of the component up to the innermost opaque border
   * @param border
   * @param component
   * @return
   */
  private static Insets getInnermostOpaqueBorderInsets (Border border, JComponent component)
  {
    Insets result = null;

    if (border != null)
    {
      if (border instanceof CompoundBorder)
      {
        CompoundBorder compoundBorder = ((CompoundBorder) border);
        Insets insets = getInnermostOpaqueBorderInsets(compoundBorder.getInsideBorder(), component);
        if (insets != null)
        {
          result = new Insets(0, 0, 0, 0);
          addInsets(result, compoundBorder.getOutsideBorder().getBorderInsets(component));
          addInsets(result, insets);
        }
        else
        {
          insets = getInnermostOpaqueBorderInsets(compoundBorder.getOutsideBorder(), component);
          if (insets != null)
          {
            result = new Insets(0, 0, 0, 0);
            addInsets(result, insets);
          }
        }
      }
      else if (border.isBorderOpaque())
      {
        result = border.getBorderInsets(component);
      }
    }

    return result;
  }

  /**
   * Add the two given insets.
   *
   * @param insetsToAddTo The insets to add the other one to.
   * @param insetsToAdd The insets to add.
   */
  private static void addInsets (Insets insetsToAddTo, Insets insetsToAdd)
  {
    insetsToAddTo.top += insetsToAdd.top;
    insetsToAddTo.bottom += insetsToAdd.bottom;
    insetsToAddTo.right += insetsToAdd.right;
    insetsToAddTo.left += insetsToAdd.left;
  }

}