package ola.jsame;

import javax.swing.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;

/**
 * Show simple method for animating a button using swing.Timer
 * The button "zooms" by drawing increasing/decreasing rectangles
 * Note: button also has Icon, this is drawn independently
 * of zooming. Most likely all drawing should be consolidated in
 * one place.
 */

public class OOGAButton extends JButton implements ActionListener
{
    private static final int DELAY = 3;       // timing delay
    private static Color BLANK = Color.WHITE; // button not visible?
    private Color myColor;                    // color of button
    private Color mySavedColor = null;        // if null, not zooming
    
    private Timer myTimer = new Timer(DELAY, this);
    private int myCount;

    // these values are used for zooming in and out
    
    private static double[] widthPercent = {
	1.0, 0.75, 0.5, 0.25, 0.5, 0.75, 1.0
    };

    private int zoomx,zoomy,zoomw,zoomh;
    
    public void actionPerformed(ActionEvent e)
    {
	int w = getWidth();
        int h = getHeight();
	myCount++;
	double factor = widthPercent[myCount % widthPercent.length];
	zoomx = (int) (w*(1.0-factor)/2.0);
	zoomy = (int) (h*(1.0-factor)/2.0);
	zoomw = (int) (w*factor);
	zoomh = (int) (h*factor);
	repaint();
    }

    public void paintComponent(Graphics g)
    {
	super.paintComponent(g);
	if (mySavedColor != null) {
	    Color c = g.getColor();
	    g.setColor(Color.BLACK);
	    g.fill3DRect(zoomx,zoomy,zoomw,zoomh,true);
	    g.setColor(c);	    
	}
    }
    
    public OOGAButton()
    {
        super();
    }

    public OOGAButton(String s)
    {
        super(s);
    }
    public OOGAButton(Icon i)
    {
        super(i);
    }
    
    public OOGAButton(String s, Icon i)
    {
        super(s,i);
    }

    public void setColor(int index)
    {
	if (index == -1){
	    myColor = BLANK;
	}
	else {
	    myColor = ourColors[index];   
	}
    }

    public Color getColor()
    {
        return myColor;
    }
    
    public void setActionCommand(String s)
    {
        super.setActionCommand(s);
    }

    public void toggleColor()
    {
        if (mySavedColor == null){
            mySavedColor = myColor;
	    myCount = (int) Math.random()*4;
	    myTimer.start();
        }
        else {
            myColor = mySavedColor;
            mySavedColor = null;
	    myTimer.stop();
        }
    }
    
    private static Color[] ourColors= {
        Color.YELLOW, Color.GREEN, Color.RED,
        Color.BLUE,   Color.CYAN,  Color.MAGENTA,
        Color.PINK,   Color.ORANGE, Color.WHITE
    };
    
}
