import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;


/**
 * This is a dialong frame that resizes the DrawSpace.
 *
 * @author Jared Mathis.
 *         Created Apr 13, 2008.
 */
public class ImageResizer extends JFrame implements ActionListener {
	private static final int FRAME_HEIGHT = 110;
	private static final int FRAME_WIDTH = 160;

	private Paint paint;
	private JTextField imageWidth;
	private JTextField imageHeight;
	
	/**
	 * Constructs an ImageResizer frame.
	 * @param paint Paint object this belongs to.
	 */
	ImageResizer(Paint paint) {
		super();
		this.paint = paint;
		
		JPanel panel = new JPanel(new GridLayout(2,2));
		JPanel panel2 = new JPanel();
		
		JLabel textWidth = new JLabel("Width:");
		panel.add(textWidth);
		
		this.imageWidth = new JTextField();
		panel.add(this.imageWidth);
		
		JLabel textHeight = new JLabel("Height: ");
		panel.add(textHeight);		
		
		this.imageHeight = new JTextField();
		panel.add(this.imageHeight);
		
		JButton okay = new JButton("Okay");
		okay.addActionListener(this);
		
		JButton cancel = new JButton("Cancel");
		cancel.addActionListener(this);
		
		panel2.add(panel);
		panel2.add(okay);
		panel2.add(cancel);
		
		this.setSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
		this.setTitle("Image Size");
		this.add(panel2);
		
	}
	
	/**
	 * Restores the fields back to whatever values the imagesize are.
	 */
	public void resetTextFileds() {
		this.imageWidth.setText(this.paint.drawSpace.img.getWidth() + "");
		this.imageHeight.setText(this.paint.drawSpace.img.getHeight() + "");
	}

	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		
		if (source instanceof JMenuItem && ((JMenuItem)source).getText() == "Resize") {
			Point location = this.paint.window.getLocation();
			location.move(
					location.x + this.paint.window.getWidth()/2 - HEIGHT/2,
					location.y + this.paint.window.getHeight()/2 - HEIGHT/2);
			
			this.setLocation(location);
			this.resetTextFileds();
			this.setVisible(true);
		}
		
		if (source instanceof JButton) {
			JButton button = (JButton)source;
			String name = button.getText();
			
			if (name == "Okay") {
				this.setVisible(false);
				this.paint.drawSpace.setImageSize(
						Integer.parseInt(this.imageWidth.getText()), 
						Integer.parseInt(this.imageHeight.getText())
						);
			}
			
			if (name == "Cancel") {
				this.setVisible(false);
			}
		}
		
		return;
	}
}
