/*
  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.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JComponent;
import javax.swing.JTabbedPane;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicTabbedPaneUI;

import net.beeger.squareness.SquarenessLookAndFeel;

/**
 * The Squareness Tabbed Pane UI delegate.
 */
public class SquarenessTabbedPaneUI extends BasicTabbedPaneUI
{
  /**
   * Create the UI delegate for the given component.
   *
   * @param component The component for which to create an UI delegate.
   * @return The created UI delegate.
   */
  public static ComponentUI createUI(JComponent component)
  {
    return new SquarenessTabbedPaneUI();
  }

  /**
   * Install the UI delegate for the given component.
   *
   * @param component The component for which to install the UI delegate.
   */
  public void installUI(JComponent component)
  {
    super.installUI(component);
    _tabbedBarMouseListener = new TabbedPaneMouseListener();
    _tabbedBarMouseMotionListener = new TabbedPaneMouseMotionListener();
    tabPane.addMouseListener(_tabbedBarMouseListener);
    tabPane.addMouseMotionListener(_tabbedBarMouseMotionListener);
  }

  /**
   * Uninstall the UI delegate from the given component.
   * <p/>
   * param component The component from which to uninstall the UI delegate.
   */
  public void uninstallUI(JComponent component)
  {
    tabPane.removeMouseListener(_tabbedBarMouseListener);
    tabPane.removeMouseMotionListener(_tabbedBarMouseMotionListener);
    super.uninstallUI(component);
  }

  /**
   * Paint the background of the tab at index tabIndex.
   *
   * @param graphics     The graphics object to use for painting.
   * @param tabPlacement The placement of the tabs (TOP, BOTTOM, LEFT, RIGHT)
   * @param tabIndex     The index of the tab to paint the background for.
   * @param x            The x position of the tab
   * @param y            The y position of the tab
   * @param width        The width of the tab
   * @param height       The height of the tab
   * @param isSelected   Is the tab currently selected?
   */
  protected void paintTabBackground(Graphics graphics, int tabPlacement, int tabIndex,
                                    int x, int y, int width, int height, boolean isSelected)
  {
    Color oldColor = graphics.getColor();

    Color background;
    if (!isSelected && _mouseOverTab == tabIndex)
    {
      background = SquarenessLookAndFeel.getCurrentSquarenessTheme().getSelectedControlBackgroundColor();
    }
    else
    {
      background = SquarenessLookAndFeel.getCurrentSquarenessTheme().getWindowBackgroundColor();
    }
    graphics.setColor(background);
    graphics.fillRect(x, y, width, height);

    graphics.setColor(oldColor);
  }

  /**
   * Paint the border of the tab at tabIndex.
   *
   * @param graphics     The graphics object to use for painting.
   * @param tabPlacement The placement of the tabs (TOP, BOTTOM, LEFT, RIGHT)
   * @param tabIndex     The index of the tab to paint the border for.
   * @param x            The x position of the tab
   * @param y            The y position of the tab
   * @param width        The width of the tab
   * @param height       The height of the tab
   * @param isSelected   Is the tab currently selected?
   */
  protected void paintTabBorder(Graphics graphics, int tabPlacement, int tabIndex,
                                int x, int y, int width, int height, boolean isSelected)
  {
    Color oldColor = graphics.getColor();

    Color borderColor;
    if (!isSelected && _mouseOverTab == tabIndex)
    {
      borderColor = SquarenessLookAndFeel.getCurrentSquarenessTheme().getSelectedControlBackgroundColor().darker();
    }
    else
    {
      borderColor = SquarenessLookAndFeel.getCurrentSquarenessTheme().getNormalBorderColor();
    }
    graphics.setColor(borderColor);

    graphics.translate(x, y);

    if (isSelected || _mouseOverTab == tabIndex)
    {
      switch (tabPlacement)
      {
        case JTabbedPane.TOP:
          paintHorizontalTabBorder(graphics, height, width, true);
          break;
        case JTabbedPane.BOTTOM:
          paintHorizontalTabBorder(graphics, height, width, false);
          break;
        case JTabbedPane.LEFT:
          paintVerticalTabBorder(graphics, height, width, true);
          break;
        case JTabbedPane.RIGHT:
          paintVerticalTabBorder(graphics, height, width, false);
          break;
      }
    }
    else
    {
      int tabCount = tabPane.getTabCount();
      if (lastTabInRun(tabCount, getRunForTab(tabCount, tabIndex)) != tabIndex
          && tabPane.getSelectedIndex() - tabIndex != 1)
      {
        switch (tabPlacement)
        {
          case JTabbedPane.TOP:
          case JTabbedPane.BOTTOM:
            graphics.drawLine(width - 1, 3, width - 1, height - 1 - 3);
            break;
          case JTabbedPane.LEFT:
          case JTabbedPane.RIGHT:
            graphics.drawLine(4, height - 1, width - 1 - 4, height - 1);
            break;
        }
      }
    }
    graphics.translate(-x, -y);
    graphics.setColor(oldColor);
  }

  /**
   * Paint a border for a vertical tab that is either selected or in mouse over mode.
   *
   * @param graphics     The graphics object to use for painting.
   * @param height       The height of the tab
   * @param width        The width of the tab.
   * @param isPlacedLeft Are the tabs placed on the left side?
   */
  private void paintVerticalTabBorder(Graphics graphics, int height, int width, boolean isPlacedLeft)
  {
    graphics.drawLine(0, 0, width - 1, 0);

    if (isPlacedLeft)
    {
      graphics.drawLine(0, 0, 0, height - 1);
      graphics.drawLine(0, height - 1, width - 1, height - 1);
    }
    else
    {
      graphics.drawLine(width - 1, 0, width - 1, height - 1);
      graphics.drawLine(0, height - 1, width - 1, height - 1);
    }
  }

  /**
   * Paint a border for a horizontal tab that is either selected or in mouse over mode.
   *
   * @param graphics    The graphics object to use for painting.
   * @param height      The height of the tab
   * @param width       The width of the tab.
   * @param isPlacedTop Are the tabs placed at the top?
   */
  private void paintHorizontalTabBorder(Graphics graphics, int height, int width, boolean isPlacedTop)
  {
    graphics.drawLine(0, 0, 0, height - 1);
    graphics.drawLine(width - 1, 0, width - 1, height - 1);

    if (isPlacedTop)
    {
      graphics.drawLine(0, 0, width - 1, 0);
    }
    else
    {
      graphics.drawLine(0, height - 1, width - 1, height - 1);
    }
  }

  /**
   * Paint the top border of the content of the tabbed pane.
   *
   * @param graphics      The graphics object to use for painting
   * @param tabPlacement  The placement of the tabs (TOP,BOTTOM,LEFT,RIGHT)
   * @param selectedIndex The index of the selected tab
   * @param x             The x position of the content pane.
   * @param y             The y position of the content pane
   * @param width         The width of the content pane
   * @param height        The height of the content pane
   */
  protected void paintContentBorderTopEdge(Graphics graphics, int tabPlacement, int selectedIndex,
                                           int x, int y, int width, int height)
  {
    Color oldColor = graphics.getColor();

    Color borderColor = SquarenessLookAndFeel.getCurrentSquarenessTheme().getNormalBorderColor();
    graphics.setColor(borderColor);

//    Rectangle selRect = selectedIndex < 0 ? null : getTabBounds(selectedIndex, calcRect);
    Rectangle selRect = selectedIndex < 0 ? null : getTabBoundsNoCheckLayout(selectedIndex);

    if (tabPlacement != TOP || selectedIndex < 0 ||
        (selRect.y + selRect.height + 1 < y) ||
        (selRect.x < x || selRect.x > x + width))
    {
      graphics.drawLine(x, y, x + width - 1, y);
    }
    else
    {
      graphics.drawLine(x, y, selRect.x, y);
      if (selRect.x + selRect.width < x + width - 1)
      {
        graphics.drawLine(selRect.x + selRect.width - 1, y, x + width - 1, y);
      }
    }

    graphics.setColor(oldColor);
  }

  /**
   * Paint the right border of the content of the tabbed pane.
   *
   * @param graphics      The graphics object to use for painting
   * @param tabPlacement  The placement of the tabs (TOP,BOTTOM,LEFT,RIGHT)
   * @param selectedIndex The index of the selected tab
   * @param x             The x position of the content pane.
   * @param y             The y position of the content pane
   * @param width         The width of the content pane
   * @param height        The height of the content pane
   */
  protected void paintContentBorderRightEdge(Graphics graphics, int tabPlacement, int selectedIndex,
                                             int x, int y, int width, int height)
  {
    Color oldColor = graphics.getColor();

    Color borderColor = SquarenessLookAndFeel.getCurrentSquarenessTheme().getNormalBorderColor();
    graphics.setColor(borderColor);

//    Rectangle selRect = selectedIndex < 0 ? null : getTabBounds(selectedIndex, calcRect);
    Rectangle selRect = selectedIndex < 0 ? null : getTabBoundsNoCheckLayout(selectedIndex);

    if (tabPlacement != RIGHT || selectedIndex < 0 ||
        (selRect.x - 1 > width) ||
        (selRect.y < y || selRect.y > y + height))
    {
      graphics.drawLine(x + width - 1, y, x + width - 1, y + height - 1);
    }
    else
    {
      graphics.drawLine(x + width - 1, y, x + width - 1, selRect.y);

      if (selRect.y + selRect.height < y + height - 1)
      {
        graphics.drawLine(x + width - 1, selRect.y + selRect.height - 1, x + width - 1, y + height - 1);
      }
    }

    graphics.setColor(oldColor);
  }

  /**
   * Paint the left border of the content of the tabbed pane.
   *
   * @param graphics      The graphics object to use for painting
   * @param tabPlacement  The placement of the tabs (TOP,BOTTOM,LEFT,RIGHT)
   * @param selectedIndex The index of the selected tab
   * @param x             The x position of the content pane.
   * @param y             The y position of the content pane
   * @param width         The width of the content pane
   * @param height        The height of the content pane
   */
  protected void paintContentBorderLeftEdge(Graphics graphics, int tabPlacement, int selectedIndex,
                                            int x, int y, int width, int height)
  {
    Color oldColor = graphics.getColor();

    Color borderColor = SquarenessLookAndFeel.getCurrentSquarenessTheme().getNormalBorderColor();
    graphics.setColor(borderColor);

//    Rectangle selRect = selectedIndex < 0 ? null : getTabBounds(selectedIndex, calcRect);
    Rectangle selRect = selectedIndex < 0 ? null : getTabBoundsNoCheckLayout(selectedIndex);

    if (tabPlacement != LEFT || selectedIndex < 0 ||
        (selRect.x + selRect.width + 1 < x) ||
        (selRect.y < y || selRect.y > y + height))
    {
      graphics.drawLine(x, y, x, y + height - 1);
    }
    else
    {
      graphics.drawLine(x, y, x, selRect.y);
      if (selRect.y + selRect.height < y + height - 1)
      {
        graphics.drawLine(x, selRect.y + selRect.height - 1, x, y + height - 1);
      }
    }

    graphics.setColor(oldColor);
  }

  /**
   * Paint the bottom border of the content of the tabbed pane.
   *
   * @param graphics      The graphics object to use for painting
   * @param tabPlacement  The placement of the tabs (TOP,BOTTOM,LEFT,RIGHT)
   * @param selectedIndex The index of the selected tab
   * @param x             The x position of the content pane.
   * @param y             The y position of the content pane
   * @param width         The width of the content pane
   * @param height        The height of the content pane
   */
  protected void paintContentBorderBottomEdge(Graphics graphics, int tabPlacement, int selectedIndex,
                                              int x, int y, int width, int height)
  {
    Color oldColor = graphics.getColor();

    Color borderColor = SquarenessLookAndFeel.getCurrentSquarenessTheme().getNormalBorderColor();
    graphics.setColor(borderColor);

//    Rectangle selRect = selectedIndex < 0 ? null : getTabBounds(selectedIndex, calcRect);
    Rectangle selRect = selectedIndex < 0 ? null : getTabBoundsNoCheckLayout(selectedIndex);

    if (tabPlacement != BOTTOM || selectedIndex < 0 ||
        (selRect.y - 1 > height) ||
        (selRect.x < x || selRect.x > x + width))
    {
      graphics.drawLine(x, y + height - 1, x + width - 1, y + height - 1);
    }
    else
    {
      graphics.drawLine(x, y + height - 1, selRect.x, y + height - 1);
      if (selRect.x + selRect.width < x + width - 1)
      {
        graphics.drawLine(selRect.x + selRect.width - 1, y + height - 1, x + width - 1, y + height - 1);
      }
    }

    graphics.setColor(oldColor);
  }

  protected boolean isTabVisible(int index)
  {
    return index < rects.length && rects[index] != null;
  }

  protected Rectangle getTabBoundsNoCheckLayout(int index)
  {
    Rectangle result = new Rectangle();
    getTabBounds(index, result);
    return result;
  }


  public void paint(Graphics g, JComponent c)
  {
    Rectangle allTabBounds = null;
    for (int i = 0; i < tabPane.getTabCount(); i++)
    {
      if (isTabVisible(i))
      {
        Rectangle tabBounds = getTabBoundsNoCheckLayout(i);
        if (allTabBounds == null)
        {
          allTabBounds = tabBounds;
        }
        else
        {
          allTabBounds.add(tabBounds);
        }
      }
    }

    if (allTabBounds != null && allTabBounds.contains(g.getClipBounds()))
    {
      if (!(tabPane.getTabLayoutPolicy() == JTabbedPane.SCROLL_TAB_LAYOUT))
      {
        paintTabArea(g, tabPane.getTabPlacement(), tabPane.getSelectedIndex());
      }
    }
    else
    {
      super.paint(g, c);
    }
  }

  /**
   * The mouse motion listener that observes wheter the tabbed pane enters or exits roll over mode.
   */
  private class TabbedPaneMouseMotionListener extends MouseMotionAdapter
  {
    public void mouseMoved(MouseEvent mouseEvent)
    {
      boolean found = false;
      for (int i = 0; !found && i < tabPane.getTabCount(); i++)
      {
        if (isTabVisible(i))
        {
          Rectangle tabBounds = getTabBoundsNoCheckLayout(i);
          if (tabBounds.contains(mouseEvent.getPoint()))
          {
            found = true;
            if (_mouseOverTab != i)
            {
              if (_mouseOverTab >= 0 && isTabVisible(_mouseOverTab) && tabPane.getSelectedIndex() != _mouseOverTab)
              {
                tabPane.repaint(getTabBoundsNoCheckLayout(_mouseOverTab));
              }
              if (tabPane.getSelectedIndex() != i)
              {
                tabPane.repaint(tabBounds);
              }
              _mouseOverTab = i;
            }
          }
        }
      }
      if (!found && _mouseOverTab >= 0)
      {
        if (_mouseOverTab < tabPane.getTabCount() && isTabVisible(_mouseOverTab) && tabPane.getSelectedIndex() != _mouseOverTab)
        {
          tabPane.repaint(getTabBoundsNoCheckLayout(_mouseOverTab));
        }
        _mouseOverTab = -1;
      }
    }
  }

  /**
   * The mouse listener that observes whether the tabbed pane exits rollover mode.
   */
  private class TabbedPaneMouseListener extends MouseAdapter
  {
    public void mouseExited(MouseEvent mouseEvent)
    {
      if (_mouseOverTab >= 0)
      {
        if (_mouseOverTab < tabPane.getTabCount() && isTabVisible(_mouseOverTab) && tabPane.getSelectedIndex() != _mouseOverTab)
        {
          tabPane.repaint(getTabBoundsNoCheckLayout(_mouseOverTab));
        }
        _mouseOverTab = -1;
      }
    }
  }

  private TabbedPaneMouseMotionListener _tabbedBarMouseMotionListener;
  private TabbedPaneMouseListener _tabbedBarMouseListener;
  private int _mouseOverTab = -1;

}