/*
 * Copyright (c) 2000-2009 TeamDev Ltd. All rights reserved.
 * TeamDev PROPRIETARY and CONFIDENTIAL.
 * Use is subject to license terms.
 */
package com.jniwrapper.win32.ui.controls;

import com.jniwrapper.win32.ui.dialogs.ChooseColorDialog;

import javax.swing.*;
import javax.swing.border.EtchedBorder;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * ChooseColorField class is a component for selecting colors that uses
 * ChooseColorDialog.
 * 
 * @author Serge Piletsky
 */
public class ChooseColorField extends AbstractChooserField
{
    public static final String PROPERTY_COLOR = "color";
    private ChooseColorDialog _dialog;

    protected JComponent createField()
    {
        Dimension size = new Dimension(60, 20);

        JComponent result = new JPanel();
        result.setPreferredSize(size);
        result.setMinimumSize(size);
        result.setMaximumSize(size);
        result.setBackground(Color.black);
        result.setBorder(new EtchedBorder(EtchedBorder.LOWERED, Color.white, Color.gray));

        result.addMouseListener(new MouseAdapter()
        {
            public void mouseClicked(MouseEvent e)
            {
                //handle double click mouse event
                if (e.getClickCount() == 2)
                {
                    actionPerformed(null);
                }
            }
        });
        return result;
    }

    public ChooseColorField()
    {
        super();
    }

    public ChooseColorField(Color color)
    {
        this();
        setColor(color);
    }

    public void actionPerformed(ActionEvent e)
    {
        ChooseColorDialog dialog = getDialog();
        Color oldColor = getColor();
        dialog.setColor(oldColor);
        if (dialog.execute())
        {
            Color newColor = dialog.getColor();
            setColor(newColor);
            firePropertyChange(PROPERTY_COLOR, oldColor, newColor);
        }
    }

    /**
     * Returns ChooseColorDialog.
     * 
     * @return dialog instance.
     */
    public ChooseColorDialog getDialog()
    {
        if (_dialog == null)
        {
            Window parent = SwingUtilities.getWindowAncestor(this);
            _dialog = new ChooseColorDialog(parent);
        }
        return _dialog;
    }

    /**
     * Returns a selected color.
     * 
     * @return selected color.
     */
    public Color getColor()
    {
        return getField().getBackground();
    }

    /**
     * Sets a color.
     * 
     * @param color
     */
    public void setColor(Color color)
    {
        getField().setBackground(color);
    }
}