package CH.ifa.draw.util;

import java.awt.Component;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.JToolBar;

import CH.ifa.draw.standard.ToolButton;

/**
 * A class that creates a new palette as a new JToolBar.
 * Provides functions to get the created toolbar and add toolButtons to the toolbar.
 */
public class Palette {
    private final JToolBar _toolBar;
    private final List<ToolButton> _toolButtons;

    /**
     * Constructs a new palette with the param title as title and as tool tip.
     * The JToolBar won't have any margin and the border of the toolbar's buttons
     * will only be visible on mouse hover.
     *
     * @param title the name of the new palette
     */
    public Palette(String title) {
        _toolButtons = new ArrayList<>();
        _toolBar = new JToolBar();
        _toolBar.setName(title);
        _toolBar.setToolTipText(title);
        _toolBar.setRollover(true);
        _toolBar.setMargin(new Insets(0, 0, 0, 0));
    }

    /**
     * Returns the toolbar of this palette.
     * <br>
     * This method also checks if the ToolButtons that were added to this palette are still included in the toolbar.
     * If the buttons are missing they are readded.
     *
     * @return {@link JToolBar} The toolbar.
     */
    public Component getComponent() {
        Component[] components = _toolBar.getComponents();
        for (ToolButton toolButton : _toolButtons) {
            AbstractButton button = toolButton.button();
            if (!Arrays.asList(components).contains(button)) {
                _toolBar.add(button);
            }
        }
        return _toolBar;
    }

    /**
     * Adds a ToolButton the palette.
     *
     * @param c the ToolButton that will be added to the palette
     * @return the JToggleButton of the ToolButton
     */
    public Component add(ToolButton c) {
        _toolButtons.add(c);
        _toolBar.add(c.button());
        return c.button();
    }
}