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

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Iterator;
import java.util.Map;
import javax.swing.LookAndFeel;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.plaf.BorderUIResource;
import javax.swing.plaf.metal.MetalLookAndFeel;

import net.beeger.squareness.theme.DefaultSquarenessTheme;
import net.beeger.squareness.theme.PropertiesSquarenessTheme;
import net.beeger.squareness.theme.SquarenessTheme;
import net.beeger.squareness.util.SquarenessBorderFactory;
import net.beeger.squareness.util.SquarenessIconFactory;
import org.jvnet.lafplugin.ComponentPluginManager;

/**
 * <p>This is the core class of the Squareness Look And Feel.</p>
 * <p>It sets up the colors, fonts, ui delegates as well as other resources and defaults
 * used by this look and feel.</p>
 */
public class SquarenessLookAndFeel extends MetalLookAndFeel
{

  public static void setCurrentSquarenessTheme(SquarenessTheme theme)
  {
    _currentSquarenessTheme = theme;
    MetalLookAndFeel.setCurrentTheme(theme);
  }

  public static SquarenessTheme getCurrentSquarenessTheme()
  {
    if (_currentSquarenessTheme == null)
    {
      loadThemePackageTheme();
    }
    if (_currentSquarenessTheme == null)
    {
      setCurrentSquarenessTheme(new DefaultSquarenessTheme());
    }
    return _currentSquarenessTheme;
  }

  public static void loadThemePackageTheme ()
  {
    final InputStream themeSelectorStream = SquarenessLookAndFeel.class.getResourceAsStream("/themeselector.slfts");
    if (themeSelectorStream != null)
    {
      Properties themeSelector = new Properties();
      try
      {
        themeSelector.load(themeSelectorStream);
        String themeFileName = themeSelector.getProperty("currentTheme");
        if (themeFileName != null && themeFileName.trim().length() > 0)
        {
          Properties theme = new Properties();
          theme.load(SquarenessLookAndFeel.class.getResourceAsStream("/" + themeFileName));
          setCurrentSquarenessTheme(new PropertiesSquarenessTheme(theme));
        }
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
      catch (PropertiesSquarenessTheme.LoadException e)
      {
        e.printStackTrace();
      }
    }
  }

  public SquarenessLookAndFeel ()
  {
  }

  /**
   * Is the look and feel a native look and feel?
   * 
   * @return true if the look and feel is a native look and feel, false otherwise
   */
  public boolean isNativeLookAndFeel ()
  {
    return false;
  }

  /**
   * <p>Is this look and feel supported on the underlying plattform?</p>
   * <p><b>Note:</b> The Squareness look and feel is supported on any available plattform. So this method always
   * returns true.</p>
   * 
   * @return true if the look and feel is supported on the underlying plattform, false otherwise.
   */
  public boolean isSupportedLookAndFeel ()
  {
    return true;
  }

  /**
   * Return the description of the look and feel.
   * 
   * @return The description of the look and feel.
   */
  public String getDescription ()
  {
    return DESCRIPTION;
  }

  /**
   * Return the id of the look and feel.
   * 
   * @return The id of the look and feel
   */
  public String getID ()
  {
    return ID;
  }

  /**
   * Return the name of the look and feel.
   * 
   * @return The name of the look and feel.
   */
  public String getName ()
  {
    return NAME;
  }

  //
  // protected interface
  //

  public void initialize ()
  {
    super.initialize();
    _plugins.initializeAll();
  }


  public void uninitialize()
  {
    super.uninitialize();
    _plugins.uninitializeAll();
  }

  /**
   * Initialize the uiClassID to BasicComponentUI mapping.
   * The JComponent classes define their own uiClassID constants
   * (see AbstractComponent.getUIClassID).  This table must
   * map those constants to a BasicComponentUI class of the
   * appropriate type.
   * 
   * @param table The table of defaults into which to put the defaults of this look and feel.
   * @see #getDefaults
   */
  protected void initClassDefaults (UIDefaults table)
  {
    super.initClassDefaults(table);
    String packageName = "net.beeger.squareness.delegate.";
    table.put("ButtonUI", packageName + "SquarenessButtonUI");
    table.put("RadioButtonUI", packageName + "SquarenessRadioButtonUI");
    table.put("CheckBoxUI", packageName + "SquarenessCheckBoxUI");
    table.put("ToolBarUI", packageName + "SquarenessToolBarUI");
    table.put("ToggleButtonUI", packageName + "SquarenessToggleButtonUI");
    table.put("ScrollBarUI", packageName + "SquarenessScrollBarUI");
    table.put("TabbedPaneUI", packageName + "SquarenessTabbedPaneUI");
    table.put("ComboBoxUI", packageName + "SquarenessComboBoxUI");
    table.put("SliderUI", packageName + "SquarenessSliderUI");
    table.put("InternalFrameUI", packageName + "SquarenessInternalFrameUI");
    table.put("SpinnerUI", packageName + "SquarenessSpinnerUI");
    table.put("RootPaneUI", packageName + "SquarenessRootPaneUI");
    table.put("ProgressBarUI", "javax.swing.plaf.basic.BasicProgressBarUI");
    table.put("SplitPaneUI", "javax.swing.plaf.basic.BasicSplitPaneUI");
  }

  protected void initComponentDefaults (UIDefaults table)
  {
    setCurrentTheme(new DefaultSquarenessTheme());
    super.initComponentDefaults(table);

    table.put(SquarenessConstants.SCROLL_ARROW_LEFT_KEY, new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getLeftIcon();
      }
    });
    table.put(SquarenessConstants.SCROLL_ARROW_RIGHT_KEY, new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getRightIcon();
      }
    });
    table.put(SquarenessConstants.SCROLL_ARROW_UP_KEY, new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getUpIcon();
      }
    });
    table.put(SquarenessConstants.SCROLL_ARROW_DOWN_KEY, new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getDownIcon();
      }
    });

    table.put(SquarenessConstants.SPIN_UP_KEY, new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getSpinUpIcon();
      }
    });
    table.put(SquarenessConstants.SPIN_DOWN_KEY, new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getSpinDownIcon();
      }
    });

    UIDefaults.LazyValue borderWithMargin = new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessBorderFactory.getControlBorderWithMargin();
      }
    };

    UIDefaults.LazyValue borderWithoutMargin = new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessBorderFactory.getControlBorderWithoutMargin();
      }
    };

    UIDefaults.LazyValue progressBarBorder = new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessBorderFactory.getProgressBarBorder();
      }
    };

    UIDefaults.LazyValue tableHeaderCellBorder = new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessBorderFactory.getTableHeaderCellBorder();
      }
    };

    table.put("Button.background", getCurrentSquarenessTheme().getNormalControlBackgroundColor());
    table.put("Button.border", borderWithMargin);

    table.put("ToggleButton.background", getCurrentSquarenessTheme().getNormalControlBackgroundColor());
    table.put("ToggleButton.border", borderWithMargin);

    table.put("RadioButton.icon", new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getRadioButtonIcon();
      }
    });

    table.put("CheckBox.icon", new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getCheckBoxIcon();
      }
    });

    UIDefaults.LazyValue emptyborder = new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return new BorderUIResource.EmptyBorderUIResource(0, 0, 0, 0);
      }
    };

    UIDefaults.LazyValue menuItemBorder = new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessBorderFactory.getMenuItemBorder();
      }
    };

    UIDefaults.LazyValue menuItemCheckIcon = new UIDefaults.LazyValue()
        {
          public Object createValue (UIDefaults table)
          {
            return SquarenessIconFactory.getMenuItemCheckIcon();
          }
        };

    UIDefaults.LazyValue menuItemArrowIcon = new UIDefaults.LazyValue()
        {
          public Object createValue (UIDefaults table)
          {
            return SquarenessIconFactory.getMenuItemArrowIcon();
          }
        };

    table.put("TextField.border", borderWithoutMargin);
    table.put("FormattedTextField.border", borderWithoutMargin);
    table.put("PasswordField.border", borderWithoutMargin);

    table.put("MenuBar.background", getCurrentSquarenessTheme().getWindowBackgroundColor());
    table.put("MenuBar.border", emptyborder);

    table.put("Menu.background", null);
    table.put("Menu.border", menuItemBorder);
    table.put("Menu.borderPainted", Boolean.TRUE);
    table.put("Menu.selectionForeground", table.get("textHighlightText"));
    table.put("Menu.selectionBackground", table.get("textHighlight"));
    table.put("Menu.arrowIcon", new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getMenuArrowIcon();
      }
    });
    table.put("Menu.checkIcon", menuItemCheckIcon);

    table.put("MenuItem.background", null);
    table.put("MenuItem.border", menuItemBorder);
    table.put("MenuItem.borderPainted", Boolean.TRUE);
    table.put("MenuItem.selectionForeground", table.get("textHighlightText"));
    table.put("MenuItem.selectionBackground", table.get("textHighlight"));
    table.put("MenuItem.checkIcon", menuItemCheckIcon);

    table.put("RadioButtonMenuItem.background", null);
    table.put("RadioButtonMenuItem.border", menuItemBorder);
    table.put("RadioButtonMenuItem.borderPainted", Boolean.TRUE);
    table.put("RadioButtonMenuItem.selectionForeground", table.get("textHighlightText"));
    table.put("RadioButtonMenuItem.selectionBackground", table.get("textHighlight"));
    table.put("RadioButtonMenuItem.checkIcon", new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getRadioButtonMenuItemCheckIcon();
      }
    });
    table.put("RadioButtonMenuItem.arrowIcon", menuItemArrowIcon);

    table.put("CheckBoxMenuItem.background", null);
    table.put("CheckBoxMenuItem.border", menuItemBorder);
    table.put("CheckBoxMenuItem.borderPainted", Boolean.TRUE);
    table.put("CheckBoxMenuItem.selectionForeground", table.get("textHighlightText"));
    table.put("CheckBoxMenuItem.selectionBackground", table.get("textHighlight"));
    table.put("CheckBoxMenuItem.checkIcon", new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getCheckBoxMenuItemCheckIcon();
      }
    });
    table.put("CheckBoxMenuItem.arrowIcon", menuItemArrowIcon);

    table.put("Separator.foreground", getCurrentSquarenessTheme().getNormalBorderColor());
    table.put("Separator.background", null);
    table.put("PopupMenu.border", new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessBorderFactory.getNonSpacingControlBorderWithoutMargin();
      }
    });

    UIDefaults.LazyValue frameBorder = new UIDefaults.LazyValue()
        {
          public Object createValue (UIDefaults table)
          {
            return SquarenessBorderFactory.getInternalFrameBorder();
          }
        };

    table.put("InternalFrame.border", frameBorder);

    table.put("InternalFrame.icon", null);
    table.put("InternalFrame.maximizeIcon", new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getMaximizeFrameIcon();
      }
    });
    table.put("InternalFrame.minimizeIcon", new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getMinimizeFrameIcon();
      }
    });
    table.put("InternalFrame.iconifyIcon", new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getIconifyFrameIcon();
      }
    });
    table.put("InternalFrame.closeIcon", new UIDefaults.LazyValue()
    {
      public Object createValue (UIDefaults table)
      {
        return SquarenessIconFactory.getCloseFrameIcon();
      }
    });

    table.put("RootPane.frameBorder", frameBorder);
    table.put("RootPane.plainDialogBorder", frameBorder);
    table.put("RootPane.informationDialogBorder", frameBorder);
    table.put("RootPane.errorDialogBorder", frameBorder);
    table.put("RootPane.colorChooserDialogBorder", frameBorder);
    table.put("RootPane.fileChooserDialogBorder", frameBorder);
    table.put("RootPane.questionDialogBorder", frameBorder);
    table.put("RootPane.warningDialogBorder", frameBorder);


    table.put("ScrollBar.thumb", getCurrentSquarenessTheme().getNormalControlBackgroundColor());
    table.put("ScrollBar.background", getCurrentSquarenessTheme().getProgressBarBackgroundColor());
    table.put("ScrollBar.width", new Integer(17));
    table.put("ScrollPane.border", borderWithoutMargin);

    table.put("TableHeader.background", getCurrentSquarenessTheme().getNormalControlBackgroundColor());

    table.put("ToolBar.border", emptyborder);
    table.put("ToolBar.background", getCurrentSquarenessTheme().getWindowBackgroundColor());

    table.put("ComboBox.border", borderWithoutMargin);
    table.put("ComboBox.background", getCurrentSquarenessTheme().getTextInputBackgroundColor());
    table.put("ComboBox.selectionBackground", table.get("textHighlight"));
    table.put("ComboBox.selectionForeground", table.get("textHighlightText"));

    table.put("ProgressBar.border", progressBarBorder);
    table.put("ProgressBar.cellLength", new Integer(1));
    table.put("ProgressBar.cellSpacing", new Integer(1));
    table.put("ProgressBar.selectionForeground", getCurrentSquarenessTheme().getTextColor());
    table.put("ProgressBar.selectionBackground", getCurrentSquarenessTheme().getTextColor());
    table.put("ProgressBar.foreground", getCurrentSquarenessTheme().getSelectedControlBackgroundColor());
    table.put("ProgressBar.background", getCurrentSquarenessTheme().getProgressBarBackgroundColor());

    table.put("SplitPane.highlight", getCurrentSquarenessTheme().getNormalBorderColor());
    table.put("SplitPane.shadow", getCurrentSquarenessTheme().getNormalBorderColor());
    table.put("SplitPane.darkShadow", getCurrentSquarenessTheme().getNormalBorderColor());
    table.put("SplitPane.border", null);
    table.put("SplitPaneDivider.border", null);

    table.put("TabbedPane.selected", getCurrentSquarenessTheme().getWindowBackgroundColor());
    table.put("TabbedPane.shadow", getCurrentSquarenessTheme().getNormalBorderColor().brighter().brighter());
    table.put("TabbedPane.darkShadow", getCurrentSquarenessTheme().getNormalBorderColor());
    table.put("TabbedPane.highlight", getCurrentSquarenessTheme().getWindowBackgroundColor().brighter().brighter());
    table.put("TabbedPane.background", getCurrentSquarenessTheme().getWindowBackgroundColor());
    table.put("TabbedPane.selected", null);
    table.put("Viewport.background", getCurrentSquarenessTheme().getWindowBackgroundColor());

    table.put("Table.scrollPaneBorder", borderWithoutMargin);
    table.put("TableHeader.cellBorder", tableHeaderCellBorder);

    table.put("Panel.background", getCurrentSquarenessTheme().getWindowBackgroundColor());
    table.put("Panel.foreground", getCurrentSquarenessTheme().getTextColor());

    table.put("Tree.collapsedIcon", LookAndFeel.makeIcon(getClass(), "icons/treecollapsed.gif"));
    table.put("Tree.expandedIcon", LookAndFeel.makeIcon(getClass(), "icons/treeexpanded.gif"));
    table.put("Tree.openIcon", LookAndFeel.makeIcon(getClass(), "icons/folderopened.gif"));
    table.put("Tree.closedIcon", LookAndFeel.makeIcon(getClass(), "icons/folderclosed.gif"));
    table.put("Tree.leafIcon", LookAndFeel.makeIcon(getClass(), "icons/document.gif"));

    table.put("FileView.directoryIcon", LookAndFeel.makeIcon(getClass(), "icons/folderclosed.gif"));
    table.put("FileView.fileIcon", LookAndFeel.makeIcon(getClass(), "icons/document.gif"));
    table.put("FileView.computerIcon", LookAndFeel.makeIcon(getClass(), "icons/computer.gif"));
    table.put("FileView.hardDriveIcon", LookAndFeel.makeIcon(getClass(), "icons/hd.gif"));
    table.put("FileView.floppyDriveIcon", LookAndFeel.makeIcon(getClass(), "icons/floppy.gif"));

    table.put("FileChooser.detailsViewIcon", LookAndFeel.makeIcon(getClass(), "icons/detail.gif"));
    table.put("FileChooser.homeFolderIcon", LookAndFeel.makeIcon(getClass(), "icons/home.gif"));
    table.put("FileChooser.listViewIcon", LookAndFeel.makeIcon(getClass(), "icons/list.gif"));
    table.put("FileChooser.newFolderIcon", LookAndFeel.makeIcon(getClass(), "icons/folderclosed.gif"));
    table.put("FileChooser.upFolderIcon", LookAndFeel.makeIcon(getClass(), "icons/folderup.gif"));

//    table.put("Spinner.background",table.get(SquarenessConstants.NORMAL_CONTROL_COLOR_KEY));
//    table.put("Spinner.foreground",table.get(SquarenessConstants.TEXT_TEXT_COLOR_KEY));
//    table.put("Spinner.border", borderWithoutMargin);

    for (Iterator iterator = table.entrySet().iterator(); iterator.hasNext();)
    {
      Map.Entry entry = (Map.Entry) iterator.next();
      if (entry.getValue() instanceof String && ((String) entry.getValue()).startsWith("sounds/"))
      {
        entry.setValue("/javax/swing/plaf/metal/" + entry.getValue());
      }
    }

    _plugins.processAllDefaultsEntries(UIManager.getDefaults(), _currentSquarenessTheme);
  }

  /**
   * Load the SystemColors into the defaults table.  The keys
   * for SystemColor defaults are the same as the names of
   * the public fields in SystemColor.  If the table is being
   * created on a native Windows platform we use the SystemColor
   * values, otherwise we create color objects whose values match
   * the defaults Windows95 colors.
   * 
   * @param table The table of defaults into which to put the defaults of this look and feel.
   */
  protected void initSystemColorDefaults (UIDefaults table)
  {
    table.put("desktop", getCurrentSquarenessTheme().getDesktopColor());
    table.put("activeCaption", getCurrentSquarenessTheme().getWindowBackgroundColor());
    table.put("activeCaptionText", getCurrentSquarenessTheme().getTextColor());
    table.put("activeCaptionBorder", getCurrentSquarenessTheme().getNormalBorderColor());
    table.put("inactiveCaption", getCurrentSquarenessTheme().getWindowBackgroundColor());
    table.put("inactiveCaptionText", getCurrentSquarenessTheme().getDisabledBorderColor());
    table.put("inactiveCaptionBorder", getCurrentSquarenessTheme().getInactiveWindowBorderColor());
    table.put("window", getCurrentSquarenessTheme().getTextInputBackgroundColor());
    table.put("windowBorder", getCurrentSquarenessTheme().getNormalBorderColor());
    table.put("windowText", getCurrentSquarenessTheme().getTextColor());
    table.put("menu", getCurrentSquarenessTheme().getProgressBarBackgroundColor());
    table.put("menuText", getCurrentSquarenessTheme().getTextColor());
    table.put("text", getCurrentSquarenessTheme().getTextInputBackgroundColor());
    table.put("textText", getCurrentSquarenessTheme().getTextColor());
    table.put("textHighlight", getCurrentSquarenessTheme().getSelectedControlBackgroundColor());
    table.put("textHighlightText", getCurrentSquarenessTheme().getTextColor());
    table.put("textInactiveText", getCurrentSquarenessTheme().getTextColor());
    table.put("control", getCurrentSquarenessTheme().getWindowBackgroundColor());
    table.put("controlText", getCurrentSquarenessTheme().getTextColor());
    table.put("controlHighlight", getCurrentSquarenessTheme().getSelectedControlBackgroundColor());
    table.put("controlLtHighlight", getCurrentSquarenessTheme().getSelectedControlBackgroundColor());
    table.put("controlShadow", getCurrentSquarenessTheme().getSelectedControlBackgroundShadowColor());
    table.put("controlDkShadow", getCurrentSquarenessTheme().getSelectedControlBackgroundShadowColor());
    table.put("scrollbar", getCurrentSquarenessTheme().getProgressBarBackgroundColor());
    table.put("info", getCurrentSquarenessTheme().getProgressBarBackgroundColor());
    table.put("infoText", getCurrentSquarenessTheme().getTextColor());
  }


  //
  // private interface
  private static final String PLUGIN_FILE_NAME = "META-INF/squareness-plugin.xml";

  private static final ComponentPluginManager _plugins = new ComponentPluginManager(PLUGIN_FILE_NAME);

  private static final String DESCRIPTION = "Squareness Look And Feel";
  private static final String ID = "Squareness";
  private static final String NAME = "Squareness";

  private static SquarenessTheme _currentSquarenessTheme;
}