package view;

import java.awt.Color;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;

import javax.swing.ImageIcon;
import javax.swing.JButton;

/**
 * A {@link NiceButton} is a {@link JButton} that has an image on it AND looks nice.
 * @author kolja
 *
 */
public class NiceButton extends JButton {
    private static final long serialVersionUID = 1L;

    /**
     * creates a {@link NiceButton}
     * @param name the name of the image file, e.g. name="test" would correspond to "/img/test.png"
     */
    public NiceButton( String name )
    {
        super( NiceButton.class.getResource( "/img/" + name + ".png" ) != null ? makeColorTransparent( new ImageIcon( NiceButton.class.getResource( "/img/" + name + ".png" ) ).getImage().getScaledInstance( 40, 40, Image.SCALE_AREA_AVERAGING ), Color.WHITE, 0 ) : new ImageIcon() );
        setSize( 40, 40 );
    }
    
    private static ImageIcon makeColorTransparent(final Image im, final Color color, int tolerance) {
        int temp = 0;
        if (tolerance < 0 || tolerance > 100) {
            temp = 0;
        } else {
            temp = tolerance * (0xFF000000 | 0xFF000000) / 100;
        }
        final int toleranceRGB = Math.abs(temp);
        final ImageFilter filter = new RGBImageFilter() {

            public int markerRGBFrom = (color.getRGB() | 0xFF000000) - toleranceRGB;
            public int markerRGBTo = (color.getRGB() | 0xFF000000) + toleranceRGB;
            
            public final int filterRGB(final int x, final int y, final int rgb) {
                if ((rgb | 0xFF000000) >= markerRGBFrom && (rgb | 0xFF000000) <= markerRGBTo) {
                    return 0x00FFFFFF & rgb;
                } else {
                    return rgb;
                }
            }
        };
        final ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
        return new ImageIcon( Toolkit.getDefaultToolkit().createImage(ip) );
    }
}
