/*
  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.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.UIManager;

import net.beeger.squareness.SquarenessLookAndFeel;

/**
 * <p>Common super class for title panes.</p>
 * <p>This class is currently subclassed in inner classes in SquarenessInternalFrameUI and SquarenessRootPaneUI.
 * Those inner classes add the specific details of handling an internal frame viz. a frame.</p>
 */
public abstract class SquarenessTitlePane extends JComponent
{
  /**
   * Create the title pane and equip it with the frame buttons.
   */
  public SquarenessTitlePane ()
  {
    _firstUpdate = true;
    _maximizeIcon = UIManager.getIcon("InternalFrame.maximizeIcon");
    _minimizeIcon = UIManager.getIcon("InternalFrame.minimizeIcon");

    _closeButton = new FrameButton();
    _closeButton.setIcon(UIManager.getIcon("InternalFrame.closeIcon"));
    _closeButton.addActionListener(new ActionListener()
    {
      public void actionPerformed (ActionEvent e)
      {
        close();
      }
    });
    _maxButton = new FrameButton();
    _maxButton.setIcon(_maximizeIcon);
    _maxButton.addActionListener(new ActionListener()
    {
      public void actionPerformed (ActionEvent e)
      {
        if(isMaximized())
        {
          restore();
        }
        else
        {
          maximize();
        }
      }
    });
    _iconifyButton = new FrameButton();
    _iconifyButton.setIcon(UIManager.getIcon("InternalFrame.iconifyIcon"));
    _iconifyButton.addActionListener(new ActionListener()
    {
      public void actionPerformed (ActionEvent e)
      {
        iconify();
      }
    });

    add(_iconifyButton);
    add(_maxButton);
    add(_closeButton);

    _titleLabel = new JLabel();
    _titleLabel.setFont(UIManager.getFont("InternalFrame.titleFont", getLocale()));
    _titleLabel.setForeground(SquarenessLookAndFeel.getCurrentSquarenessTheme().getTextColor());
    add(_titleLabel);

    setLayout(new SquarenessTitlePaneLayout());
    setBackground(SquarenessLookAndFeel.getCurrentSquarenessTheme().getWindowBackgroundColor());
  }

  /**
   * <p>Update the title pane</p>
   * <p>This updates the title, the enabled state of the buttons and the icon on the maximize/restore button.</p>
   */
  protected void update()
  {
    boolean closeable = isClosable();
    boolean iconifiable = isIconifiable();
    boolean maximized = isMaximized();
    boolean maximizable = isMaximizable();
    Font font = UIManager.getFont("InternalFrame.titleFont", getLocale());
    String title = getTitle();

    if (_firstUpdate || _lastCloseable != closeable)
    {
      _closeButton.setEnabled(closeable);
    }
    if (_firstUpdate || _lastIconifiable != iconifiable)
    {
      _iconifyButton.setEnabled(iconifiable);
    }

    if (_firstUpdate || _lastMaximized != maximized)
    {
      _maxButton.setIcon(maximized ? _minimizeIcon : _maximizeIcon);
    }
    if (_firstUpdate || _lastMaximizable != maximizable)
    {
      _maxButton.setEnabled(maximizable);
    }

    if (_firstUpdate || !font.equals(_lastFont))
    {
      _titleLabel.setFont(font);
    }
    if (_firstUpdate || (title == null && _lastTitle != null) || (title != null && !title.equals(_lastTitle)))
    {
      _titleLabel.setText(title);
    }

    _lastCloseable = closeable;
    _lastIconifiable = iconifiable;
    _lastMaximized = maximized;
    _lastMaximizable = maximizable;
    _lastFont = font;
    _lastTitle = title;

    _firstUpdate = false;
  }

  /**
   * Do we have a left to right orientation?
   *
   * @return True if we are in left to right orientation, false otherwise.
   */
  public abstract boolean isLeftToRight();

  protected abstract boolean isIconifiable ();
  protected abstract boolean isMaximizable ();
  protected abstract boolean isClosable ();

  /**
   * Close the (internal) frame.
   */
  protected abstract void close();

  /**
   * Iconify the (internal) frame.
   */
  protected abstract void iconify();

  /**
   * Maximize the (internal) frame.
   */
  protected abstract void maximize();

  /**
   * Restore the (internal) frame.
   */
  protected abstract void restore();

  /**
   * Can the (internal) frame this title pane belongs to be maximized?
   * @return true if the (internal) frame can be maximized.
   */
  protected abstract boolean isMaximized();

  /**
   * Can the (internal) frame this title pane belongs to be iconified?
   * @return true if the (internal) frame can be iconified.
   */
  protected abstract boolean isIconified();

  /**
   * Return the title of the (internal) frame.
   * @return The title of the (internal) frame.
   */
  protected abstract String getTitle();

  private Icon _maximizeIcon;
  private Icon _minimizeIcon;
  private JButton _closeButton;
  private JButton _maxButton;
  private JButton _iconifyButton;
  private JLabel _titleLabel;

  /**
   * The layout manager of the Squareness title pane. It puts the buttons and the title on their right places.
   */
  protected class SquarenessTitlePaneLayout implements LayoutManager
  {
    /**
     * Removes the specified component from the layout.
     *
     * @param comp the component to be removed
     */
    public void removeLayoutComponent (Component comp)
    {

    }

    /**
     * If the layout manager uses a per-component string,
     * adds the component <code>comp</code> to the layout,
     * associating it
     * with the string specified by <code>name</code>.
     *
     * @param name the string to be associated with the component
     * @param comp the component to be added
     */
    public void addLayoutComponent (String name, Component comp)
    {

    }

    /**
     * Calculates the minimum size dimensions for the specified
     * container, given the components it contains.
     *
     * @param parent the component to be laid out
     * @see #preferredLayoutSize
     */
    public Dimension minimumLayoutSize (Container parent)
    {
      return new Dimension(_closeButton.getIcon().getIconWidth() + 60, _closeButton.getIcon().getIconHeight() + 2);
    }

    /**
     * Calculates the preferred size dimensions for the specified
     * container, given the components it contains.
     *
     * @param parent the container to be laid out
     * @see #minimumLayoutSize
     */
    public Dimension preferredLayoutSize (Container parent)
    {
      return minimumLayoutSize(parent);
    }

    public void layoutContainer (Container container)
    {
      boolean leftToRight = isLeftToRight();

      int width = getWidth();
      int height = getHeight();
      int x;

      int buttonHeight = _closeButton.getIcon().getIconHeight();
      int buttonWidth = _closeButton.getIcon().getIconWidth();
      int y = (height - buttonHeight) >> 1;

      x = (leftToRight) ? width - buttonWidth - 2 : 2;

      _closeButton.setBounds(x, y, buttonWidth, buttonHeight);
      x += (leftToRight) ? -(buttonWidth + 2) : buttonWidth + 2;
      _maxButton.setBounds(x, y, buttonWidth, buttonHeight);
      x += (leftToRight) ? -(buttonWidth + 2) : buttonWidth + 2;
      _iconifyButton.setBounds(x, y, buttonWidth, buttonHeight);

      int maxX = leftToRight ? x - 2 : width - 2;
      x = leftToRight ? 2 : x + 2;
      _titleLabel.setBounds(x, y, maxX - x, buttonHeight);
    }
  }

  /**
   * A convenience class used for the frame buttons.
   * Instances of this class have no borders, no margins and are not focusable.
   */
  protected static class FrameButton extends JButton
  {
    /**
     * Creates a button with no set text or icon.
     */
    public FrameButton ()
    {
      setMargin(new Insets(0,0,0,0));
      setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
      setOpaque(true);
      setFocusPainted(false);
    }

    /**
     * Returns whether this Component can be focused.
     *
     * @return <code>true</code> if this Component is focusable;
     *         <code>false</code> otherwise.
     * @see #setFocusable
     * @since 1.4
     */
    public boolean isFocusable ()
    {
      return false;
    }
  }

  private boolean _lastCloseable;
  private boolean _lastIconifiable;
  private boolean _lastMaximized;
  private boolean _lastMaximizable;
  private Font _lastFont;
  private String _lastTitle;
  private boolean _firstUpdate;
}