import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import net.quadium.toys.*;

public class DateApplet extends Applet
                        implements ActionListener, ItemListener {
    TextField entry, display;
    Choice whichStyle;
    FriendlyDate date;
    Checkbox mdyBox, zeroBox;

    public void init() {
        // make the background fit in
        boolean colorSet = false;
        try {
            setBackground(Color.decode(getParameter("bgcolor")));
            colorSet = true;
            setForeground(Color.decode(getParameter("fgcolor")));
        } catch (Exception e) {}
        
	date = new FriendlyDate();
	
	// text fields
	entry = new TextField("<enter a date here in any format>");
	entry.addActionListener(this);
	display = new TextField("<parsed date appears here>");
	display.setEditable(false);
	
	// choice menu
	whichStyle = new Choice();
	whichStyle.addItemListener(this);
	whichStyle.add("ISO_STANDARD");
	whichStyle.add("DMY");
	whichStyle.add("MDY");
	whichStyle.add("LONG_WITH_COMMA");
	whichStyle.add("DMY_MONTH_ABBREV");
	whichStyle.add("DMY_MONTH_FULL");
        if (colorSet) {
            whichStyle.setBackground(Color.white);
            whichStyle.setForeground(Color.black);
        }

	// clicky boxes
	mdyBox = new Checkbox("Try MDY first for ambiguous?", true);
	mdyBox.addItemListener(this);
	zeroBox = new Checkbox("Pad 1-digit fields with 0s?", true);
	zeroBox.addItemListener(this);
	
	// drop 'em in!
        setFont(new Font("SansSerif", Font.PLAIN, 12));
	GridBagLayout gb = new GridBagLayout();
	GridBagConstraints c = new GridBagConstraints();
	setLayout(gb);

	c.fill = GridBagConstraints.HORIZONTAL;
	c.gridwidth = GridBagConstraints.REMAINDER;
	gb.setConstraints(entry, c);
	add(entry);
	gb.setConstraints(display, c);
	add(display);
	c.gridwidth = GridBagConstraints.RELATIVE;
	Label l = new Label("Display style: ");
	gb.setConstraints(l, c);
	add(l);
	c.gridwidth = GridBagConstraints.REMAINDER;
	gb.setConstraints(whichStyle, c);
	add(whichStyle);
	c.fill = GridBagConstraints.NONE;
        c.anchor = GridBagConstraints.WEST;
	gb.setConstraints(zeroBox, c);
	add(zeroBox);
	gb.setConstraints(mdyBox, c);
	add(mdyBox);
	validate();
    }

    void doIt() {
	try {
	    date.setPreferMDY(mdyBox.getState());
	    date.parse(entry.getText());
	    display.setText(date.toString(whichStyle.getSelectedIndex(),
					  zeroBox.getState()));
	} catch (IllegalArgumentException e) {
	    display.setText("<invalid date>");
	}
    }
    
    public void actionPerformed(ActionEvent event) {
	doIt();
    }

    public void itemStateChanged(ItemEvent event) {
	if (event.getSource() == whichStyle)
	    zeroBox.setState(whichStyle.getSelectedIndex() == 0);
	doIt();
    }
}
