import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;


/**
 * Dialog for limit view of appointments.
 *
 * @author Dave Knauer, SE 376.
 */ 
public class LimitDialog extends JPanel {
	
	protected JComboBox day, month, year;
	protected JLabel dayL, monthL, yearL;
	protected GregorianCalendar cal = new GregorianCalendar();
	
	/**
	 * Sets all of the GUI elements.
	 */
	public LimitDialog() {
		this.setPreferredSize(new Dimension(100,80));
		this.setLayout(null);
		//Year
		this.yearL = new JLabel("Year");
		this.yearL.setBounds(5, 5, 60, 20);
		this.add(this.yearL);
		int curYear = cal.get(Calendar.YEAR);
		Integer years[] = new Integer[12];
		for (int i = 0; i < 12; i++) {
			years[i] = new Integer(curYear + i);
		}
		this.year = new JComboBox(years);
		this.year.setBounds(5, 25, 60, 20);
		this.add(this.year);
		//Month
		this.monthL = new JLabel("Month");
		this.monthL.setBounds(80, 5, 60, 20);
		this.add(this.monthL);
		int curMonth = cal.get(Calendar.MONTH);
		Integer months[] = new Integer[12];
		for (int i = 0; i < 12; i++) {
			months[i] = new Integer(1 + i);
		}		
		this.month = new JComboBox(months);
		this.month.setBounds(80, 25, 60, 20);
		this.month.setSelectedIndex(curMonth);
		this.add(this.month);
		//Day
		this.dayL = new JLabel("Day");
		this.dayL.setBounds(155, 5, 60, 20);
		this.add(this.dayL);
		Integer selMonth = (Integer) this.month.getSelectedItem();
		Integer selYear = (Integer) this.year.getSelectedItem();
		int maxDays = MaxDays(selMonth.intValue(),selYear.intValue());
		Integer days[] = new Integer[maxDays];
		for (int i = 0; i < maxDays; i++) {
			days[i] = new Integer(1 + i);
		}
		this.day = new JComboBox(days);
		this.day.setBounds(155, 25, 60, 20);
		if (cal.get(Calendar.DAY_OF_MONTH) <= maxDays)
			this.day.setSelectedIndex(cal.get(Calendar.DAY_OF_MONTH) - 1);
		else
			this.day.setSelectedIndex(0);
		this.add(this.day);
	}	
	
	/**
	 * Returns the max number of days for the given month/year combination.
	 *
	 * @param month The current selected month.
	 * @param year The current selected year.
	 * @return The max days for the month/year.
	 */
	private int MaxDays(int month, int year) {
		int maxDays = 0;
		switch(month) {
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				maxDays = 31;
				break;
			case 2: 
				if(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
					maxDays = 29;
				else
					maxDays = 28;
				break;
			case 4:
			case 6:
			case 9:
			case 11:
				maxDays = 30;
				break;
			default:
				maxDays = 31;
				break;
		}
		return maxDays;
	}			
}
