/*
 * File: CurrConvUsingInnerClasses.java
 * ------------------------------------
 * This program implements a simple currency converter.  This version
 * uses anonymous inner classes to specify the action listeners.
 */

import acm.gui.*;
import acm.program.*;
import java.awt.event.*;
import javax.swing.*;

public class CurrConvUsingInnerClasses extends Program {

/** Initialize the graphical user interface */
	public void init() {
		setLayout(new TableLayout(3, 2));
		currencyTable = new CurrencyTable();
		leftChooser = new JComboBox(currencyTable.getCurrencyNames());
		rightChooser = new JComboBox(currencyTable.getCurrencyNames());
		leftField = new DoubleField();
		rightField = new DoubleField();
		JButton leftButton = new JButton("Convert ->");
		JButton rightButton = new JButton("<- Convert");
		ActionListener convertLeftToRight = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				double fromValue = leftField.getValue();
				double fromRate = getRateFromChooser(leftChooser);
				double toRate = getRateFromChooser(rightChooser);
				double toValue = fromValue * fromRate / toRate;
				rightField.setValue(toValue);
			}
		};
		ActionListener convertRightToLeft = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				double fromValue = rightField.getValue();
				double fromRate = getRateFromChooser(rightChooser);
				double toRate = getRateFromChooser(leftChooser);
				double toValue = fromValue * fromRate / toRate;
				leftField.setValue(toValue);
			}
		};
		leftChooser.setSelectedItem("US Dollar");
		rightChooser.setSelectedItem("Euro");
		leftField.setFormat("0.00");
		leftField.addActionListener(convertLeftToRight);
		rightField.setFormat("0.00");
		rightField.addActionListener(convertRightToLeft);
		rightField.addActionListener(this);
		leftButton.addActionListener(convertLeftToRight);
		rightButton.addActionListener(convertRightToLeft);
		add(leftChooser);
		add(rightChooser);
		add(leftField);
		add(rightField);
		add(leftButton);
		add(rightButton);
	}

/* Gets a rate from the specified chooser */
	private double getRateFromChooser(JComboBox chooser) {
		String currencyName = (String) chooser.getSelectedItem();
		return currencyTable.getExchangeRate(currencyName);
	}

/* Private instance variables */
	private CurrencyTable currencyTable;
	private JComboBox leftChooser;
	private JComboBox rightChooser;
	private DoubleField leftField;
	private DoubleField rightField;


/** Set the program dimensions */
	public static final int APPLICATION_WIDTH = 350;
	public static final int APPLICATION_HEIGHT = 200;

/* Standard Java entry point */
/* This method can be eliminated in most Java environments */
	public static void main(String[] args) {
		new CurrConvUsingInnerClasses().start(args);
	}
}
