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

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JScrollBar;
import javax.swing.SwingConstants;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicScrollBarUI;

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

/**
 * The Squareness Scroll Bar UI delegate.
 */
public class SquarenessScrollBarUI extends BasicScrollBarUI
{
  /**
   * Create the ui delegate for the given component
   * 
   * @param component The component for which to create the ui delegate
   * @return The created ui delegate
   */
  public static ComponentUI createUI (JComponent component)
  {
    return new SquarenessScrollBarUI();
  }

  /**
   * Install this UI delegate for the given component.
   *
   * @param component The component to install this UI delegate for,.
   */
  public void installUI (JComponent component)
  {
    component.putClientProperty(SquarenessConstants.ROLLOVER_CLENT_PROPERTY_KEY, Boolean.FALSE);
    component.putClientProperty(SquarenessConstants.SCROLLBAR_THUMB_PRESSED_CLIENT_PROPERTY_KEY, Boolean.FALSE);
    component.putClientProperty(SquarenessConstants.SCROLLBAR_TRACK_PRESSED_CLIENT_PROPERTY_KEY, Boolean.FALSE);
    _scrollBarMouseMotionListener = new ScrollBarMouseMotionListener();
    _scrollBarMouseListener = new ScrollBarMouseListener();
    component.addMouseMotionListener(_scrollBarMouseMotionListener);
    component.addMouseListener(_scrollBarMouseListener);
    super.installUI(component);
  }

  /**
   * Uninstall this UI delegate from the given component.
   *
   * @param component The component to uninstall this UI delegate from.
   */
  public void uninstallUI (JComponent component)
  {
    component.removeMouseMotionListener(_scrollBarMouseMotionListener);
    component.removeMouseListener(_scrollBarMouseListener);
    super.uninstallUI(component);
  }

  /**
   * Paint the thumb of the scroll bar.
   *
   * @param graphics The graphics object used to paint the thumb.
   * @param component The component (the scroll bar) to paint the thumb for.
   * @param thumbBounds The bounds of the thumb.
   */
  protected void paintThumb (Graphics graphics, JComponent component, Rectangle thumbBounds)
  {
    Color oldColor = graphics.getColor();

    boolean isRollover = scrollbar.getClientProperty(SquarenessConstants.ROLLOVER_CLENT_PROPERTY_KEY).equals(
       Boolean.TRUE);
    boolean isPressed = scrollbar.getClientProperty(SquarenessConstants.SCROLLBAR_THUMB_PRESSED_CLIENT_PROPERTY_KEY)
       .equals(Boolean.TRUE);

    Color thumbFillColor;
    if (isRollover || isPressed)
    {
      thumbFillColor = SquarenessLookAndFeel.getCurrentSquarenessTheme().getSelectedControlBackgroundColor();
    }
    else
    {
      thumbFillColor = SquarenessLookAndFeel.getCurrentSquarenessTheme().getNormalControlBackgroundColor();
    }
    graphics.setColor(thumbFillColor);
    graphics.fillRect(thumbBounds.x, thumbBounds.y, thumbBounds.width - 1, thumbBounds.height - 1);

    if (isPressed)
    {
      graphics.setColor(SquarenessLookAndFeel.getCurrentSquarenessTheme().getSelectedControlBackgroundShadowColor());
      graphics.fillRect(thumbBounds.x + 1, thumbBounds.y + 1, thumbBounds.width - 2, 2);
      graphics.fillRect(thumbBounds.x + 1, thumbBounds.y + 1, 2, thumbBounds.height - 2);
    }

    graphics.setColor(SquarenessLookAndFeel.getCurrentSquarenessTheme().getNormalBorderColor());
    graphics.drawRect(thumbBounds.x, thumbBounds.y, thumbBounds.width - 1, thumbBounds.height - 1);

    paintGripper(graphics, thumbBounds, thumbFillColor, isPressed, isRollover);

    graphics.setColor(oldColor);
  }

  /**
   * Paint the gripper for the scroll bar.
   *
   * @param graphics The graphics object used to paint the gripper.
   * @param thumbBounds The bounds of the thumb to paint the gripper on.
   * @param thumbFillColor The color with which the thumb is currently filled.
   * @param isThumbPressed Is the thumb currently pressed?
   * @param isThumbRollover Is the thumb currently in rollover mode?
   */
  private void paintGripper (Graphics graphics, Rectangle thumbBounds, Color thumbFillColor, boolean isThumbPressed,
                             boolean isThumbRollover)
  {
    boolean isHorizontal = scrollbar.getOrientation() == SwingConstants.HORIZONTAL;
    if ((isHorizontal && thumbBounds.getWidth() > 16) || (!isHorizontal && thumbBounds.getHeight() > 16))
    {
      int translatedX = 0;
      int translatedY = 0;
      Color shadow = thumbFillColor.darker();
      Color highlight = thumbFillColor.brighter();
      translatedX = thumbBounds.x + (thumbBounds.width >> 1) - 3;
      translatedY = thumbBounds.y + (thumbBounds.height >> 1) - 3;
      graphics.translate(translatedX, translatedY);
      if(isHorizontal)
      {
        if (isThumbPressed || isThumbRollover)
        {
          graphics.translate(0, 1);

          graphics.setColor(shadow);
          paintHorizontalGripperPart(graphics);

          graphics.setColor(highlight);
          graphics.translate(1, 1);
          paintHorizontalGripperPart(graphics);
          graphics.translate(- 1, - 1);

          graphics.translate(0, - 1);
        }
        else
        {
          graphics.setColor(highlight);
          paintHorizontalGripperPart(graphics);

          graphics.setColor(shadow);
          graphics.translate(1, 1);
          paintHorizontalGripperPart(graphics);
          graphics.translate(- 1, - 1);
        }
      }
      else
      {
        if (isThumbPressed || isThumbRollover)
        {
          graphics.translate(1, 0);

          graphics.setColor(shadow);
          paintVerticalGripperPart(graphics);

          graphics.setColor(highlight);
          graphics.translate(1, 1);
          paintVerticalGripperPart(graphics);
          graphics.translate(- 1, - 1);

          graphics.translate(-1, 0);
        }
        else
        {
          graphics.setColor(highlight);
          paintVerticalGripperPart(graphics);

          graphics.setColor(shadow);
          graphics.translate(1, 1);
          paintVerticalGripperPart(graphics);
          graphics.translate(- 1, - 1);
        }
      }
      graphics.translate(-translatedX, -translatedY);
    }
  }

  /**
   * Paint one part of the gripper for a vertical scroll bar.
   * A gripper conists of two parts, the highlight and the shadow part. They have the same structure.
   * The only difference is that they are painted on different positions.
   *
   * @param graphics The graphics object used to paint the part.
   */
  protected void paintVerticalGripperPart (Graphics graphics)
  {
    paintVerticalGripperPartColumn(graphics);

    graphics.translate(4, 0);
    paintVerticalGripperPartColumn(graphics);
    graphics.translate(-4, 0);
  }

  /**
   * Each vertical gripper part consists of two columns that look the same. The operation
   * calling this operation has to translate the graphics to the right position.
   *
   * @param graphics The graphics object used to paint the part column.
   */
  protected void paintVerticalGripperPartColumn (Graphics graphics)
  {
    graphics.drawLine(0, 0, 1, 0);
    graphics.drawLine(0, 2, 1, 2);
    graphics.drawLine(0, 4, 1, 4);
    graphics.drawLine(0, 6, 1, 6);
  }

  /**
   * Paint one part of the gripper for a horizontal scroll bar.
   * A gripper conists of two parts, the highlight and the shadow part. They have the same structure.
   * The only difference is that they are painted on different positions.
   *
   * @param graphics The graphics object used to paint the part.
   */
  protected void paintHorizontalGripperPart (Graphics graphics)
  {
    paintHorizontalGripperPartRow(graphics);

    graphics.translate(0, 4);
    paintHorizontalGripperPartRow(graphics);
    graphics.translate(0, -4);
  }

  /**
   * Each horizontal gripper part consists of two columns that look the same. The operation
   * calling this operation has to translate the graphics to the right position.
   *
   * @param graphics The graphics object used to paint the part column.
   */
  protected void paintHorizontalGripperPartRow (Graphics graphics)
  {
    graphics.drawLine(0, 0 , 0, 1);
    graphics.drawLine(2, 0 , 2, 1);
    graphics.drawLine(4, 0 , 4, 1);
    graphics.drawLine(6, 0 , 6, 1);
  }

  /**
   * Paint the track of the scroll bar.
   *
   * @param graphics The graphics object used to paint the track.
   * @param component The component (the scroll bar) to paint the track for.
   * @param trackBounds The bounds of the track to paint.
   */
  protected void paintTrack (Graphics graphics, JComponent component, Rectangle trackBounds)
  {
    Color oldColor = graphics.getColor();

    if (Boolean.TRUE.equals(scrollbar.getClientProperty(SquarenessConstants.SCROLLBAR_TRACK_PRESSED_CLIENT_PROPERTY_KEY)))
    {
      graphics.setColor(SquarenessLookAndFeel.getCurrentSquarenessTheme().getPressedScrollBarTrackBackgroundColor());
    }
    else
    {
      graphics.setColor(SquarenessLookAndFeel.getCurrentSquarenessTheme().getProgressBarBackgroundColor());
    }
    graphics.fillRect(trackBounds.x, trackBounds.y, trackBounds.width - 1, trackBounds.height - 1);
    graphics.setColor(SquarenessLookAndFeel.getCurrentSquarenessTheme().getNormalBorderColor());

    if (scrollbar.getOrientation() == JScrollBar.VERTICAL)
    {
      graphics.drawLine(trackBounds.x, 0, trackBounds.x, scrollbar.getHeight() - 1);
      graphics.drawLine(trackBounds.width - 1, 0, trackBounds.width - 1, scrollbar.getHeight() - 1);
    }
    else
    {
      graphics.drawLine(0, trackBounds.y, scrollbar.getWidth() - 1, trackBounds.y);
      graphics.drawLine(0, trackBounds.height - 1, scrollbar.getWidth() - 1, trackBounds.height - 1);
    }

    graphics.setColor(oldColor);
  }

  /**
   * Create the button that is used to scroll down or right the scroll bar.
   *
   * @param orientation The orientation of the scrollbar (JScrollBar.HORIZONTAL or JScrollBar.VERTICAL)
   * @return The created button
   */
  protected JButton createIncreaseButton (int orientation)
  {
    UIDefaults defaults = UIManager.getDefaults();
    int scrollbarWidth = defaults.getInt("ScrollBar.width");
    final JButton button = new SquarenessScrollBarButton();
    Dimension dimension = new Dimension(scrollbarWidth, scrollbarWidth);
    button.setPreferredSize(dimension);
    button.setMinimumSize(dimension);
    if (scrollbar.getOrientation() == JScrollBar.HORIZONTAL)
    {
      button.setIcon(defaults.getIcon(SquarenessConstants.SCROLL_ARROW_RIGHT_KEY));
    }
    else
    {
      button.setIcon(defaults.getIcon(SquarenessConstants.SCROLL_ARROW_DOWN_KEY));
    }
    button.setHorizontalAlignment(SwingConstants.CENTER);
    button.setVerticalAlignment(SwingConstants.CENTER);
    return button;
  }

  /**
   * Create the button that is used to scroll up or left the scroll bar.
   *
   * @param orientation The orientation of the scrollbar (JScrollBar.HORIZONTAL or JScrollBar.VERTICAL)
   * @return The created button
   */
  protected JButton createDecreaseButton (int orientation)
  {
    UIDefaults defaults = UIManager.getDefaults();
    int scrollbarWidth = defaults.getInt("ScrollBar.width");
    final JButton button = new SquarenessScrollBarButton();
    Dimension dimension = new Dimension(scrollbarWidth, scrollbarWidth);
    button.setPreferredSize(dimension);
    button.setMinimumSize(dimension);
    if (scrollbar.getOrientation() == JScrollBar.HORIZONTAL)
    {
      button.setIcon(defaults.getIcon(SquarenessConstants.SCROLL_ARROW_LEFT_KEY));
    }
    else
    {
      button.setIcon(defaults.getIcon(SquarenessConstants.SCROLL_ARROW_UP_KEY));
    }
    button.setHorizontalAlignment(SwingConstants.CENTER);
    button.setVerticalAlignment(SwingConstants.CENTER);
    return button;
  }

  private static class SquarenessScrollBarButton extends JButton
  {
    public Border getBorder ()
    {
      return _border;
    }

    private Border _border = SquarenessBorderFactory.getNonSpacingControlBorderWithMargin();
  }
  /**
   * The mouse motion listener that observes wheter the scroll bar enters or exits roll over mode.
   * The client property SquarenessConstants.ROLLOVER_CLENT_PROPERTY_KEY is changed on the scroll bar accordingly.
   */
  private class ScrollBarMouseMotionListener extends MouseMotionAdapter
  {
    public void mouseMoved (MouseEvent mouseEvent)
    {
      Rectangle thumbBounds = getThumbBounds();
      if (thumbBounds.contains(mouseEvent.getPoint()))
      {
        if (scrollbar.getClientProperty(SquarenessConstants.ROLLOVER_CLENT_PROPERTY_KEY).equals(Boolean.FALSE))
        {
          scrollbar.putClientProperty(SquarenessConstants.ROLLOVER_CLENT_PROPERTY_KEY, Boolean.TRUE);
          scrollbar.repaint(thumbBounds);
        }
      }
      else
      {
        if (scrollbar.getClientProperty(SquarenessConstants.ROLLOVER_CLENT_PROPERTY_KEY).equals(Boolean.TRUE))
        {
          scrollbar.putClientProperty(SquarenessConstants.ROLLOVER_CLENT_PROPERTY_KEY, Boolean.FALSE);
          scrollbar.repaint(thumbBounds);
        }
      }
    }
  }

  /**
   * The mouse listener that observes whether the thumb or track are clicked and sets the according
   * client properties SquarenessConstants.SCROLLBAR_THUMB_PRESSED_CLIENT_PROPERTY_KEY
   */
  private class ScrollBarMouseListener extends MouseAdapter
  {
    public void mousePressed (MouseEvent mouseEvent)
    {
      Rectangle thumbBounds = getThumbBounds();
      Rectangle trackBounds = getTrackBounds();
      if (thumbBounds.contains(mouseEvent.getPoint())
          && scrollbar.getClientProperty(SquarenessConstants.SCROLLBAR_THUMB_PRESSED_CLIENT_PROPERTY_KEY).equals(
             Boolean.FALSE))
      {
        scrollbar.putClientProperty(SquarenessConstants.SCROLLBAR_THUMB_PRESSED_CLIENT_PROPERTY_KEY, Boolean.TRUE);
        scrollbar.repaint(thumbBounds);
      }
      else if (trackBounds.contains(mouseEvent.getPoint())
               && scrollbar.getClientProperty(SquarenessConstants.SCROLLBAR_TRACK_PRESSED_CLIENT_PROPERTY_KEY).equals(
         Boolean.FALSE))
      {
        scrollbar.putClientProperty(SquarenessConstants.SCROLLBAR_TRACK_PRESSED_CLIENT_PROPERTY_KEY, Boolean.TRUE);
        scrollbar.repaint(trackBounds);
      }
    }

    public void mouseReleased (MouseEvent mouseEvent)
    {
      Rectangle thumbBounds = getThumbBounds();
      Rectangle trackBounds = getTrackBounds();
      if (scrollbar.getClientProperty(SquarenessConstants.SCROLLBAR_THUMB_PRESSED_CLIENT_PROPERTY_KEY).equals(
         Boolean.TRUE))
      {
        scrollbar.putClientProperty(SquarenessConstants.SCROLLBAR_THUMB_PRESSED_CLIENT_PROPERTY_KEY, Boolean.FALSE);
        scrollbar.repaint(thumbBounds);
      }
      else if (scrollbar.getClientProperty(SquarenessConstants.SCROLLBAR_TRACK_PRESSED_CLIENT_PROPERTY_KEY).equals(
         Boolean.TRUE))
      {
        scrollbar.putClientProperty(SquarenessConstants.SCROLLBAR_TRACK_PRESSED_CLIENT_PROPERTY_KEY, Boolean.FALSE);
        scrollbar.repaint(trackBounds);
      }
    }

    public void mouseExited (MouseEvent mouseEvent)
    {
      if (scrollbar.getClientProperty(SquarenessConstants.ROLLOVER_CLENT_PROPERTY_KEY).equals(Boolean.TRUE))
      {
        scrollbar.putClientProperty(SquarenessConstants.ROLLOVER_CLENT_PROPERTY_KEY, Boolean.FALSE);
        scrollbar.repaint(getThumbBounds());
      }
    }
  }

  private ScrollBarMouseMotionListener _scrollBarMouseMotionListener;
  private ScrollBarMouseListener _scrollBarMouseListener;

}