import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.HashMap;

import javax.swing.JFrame;

/*
 * Note the power of TRIALS and NUM_DICE
 */
public class Display extends JFrame implements MouseListener {
	private final int TRIALS = 10000;

	private final int NUM_DICE = 4;
	private final int MIN_ROLL = NUM_DICE;
	private final int SIDES = 6;
	private final int MAX_ROLL = NUM_DICE * SIDES;
	
	private final int OUTCOMES = MAX_ROLL - MIN_ROLL + 1;
	private final double CAPACITY_MULTIPLIER = 1.3;
	private HashMap<Integer, Integer> hm = 
			new HashMap<Integer, Integer>(
					(int) (OUTCOMES * CAPACITY_MULTIPLIER + 1));

	public Display () {
		init();
	}

	public void init() {
		setSize(650,700);
		setBackground(Color.WHITE);
		setTitle("AWSUM!@(!*(*@(@#??@1! Histogram Thing");
		addMouseListener(this);
		histogram();
		repaint();
	}
	
	private void initHashMap() {
		for (int i = MIN_ROLL; i <= MAX_ROLL; i++) {
			hm.put(i, 0);
		}
	}

	public void histogram() {
		Die[] die = new Die[NUM_DICE];
		
		for (int i = 0; i < die.length; i++) {
			die[i] = new Die(SIDES);
		}

		initHashMap();

		for (int i = 0; i < TRIALS; i++) {
			int sum = 0;
			for (int j = 0; j < die.length; j++) {
				sum += die[j].roll();
			}
			// Increment the value corresponding to the key
			hm.put(sum, hm.get(sum) + 1);
		}
	}

	public void paint(Graphics g) {
		int yAxisXPos = 50;
		int xAxisYPos = getHeight() - 50;
		clearDisplay(g);
		g.setColor(Color.BLACK);
		drawAxes(g, yAxisXPos, xAxisYPos);
		drawNums(g, yAxisXPos, xAxisYPos);
		g.setColor(Color.BLUE);
		drawBars(g, yAxisXPos, xAxisYPos);
	}

	public void clearDisplay(Graphics g) {
		Color c = g.getColor();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, getWidth(), getHeight());
		g.setColor(c);
	}

	public void drawAxes(Graphics g, int xPos, int yPos) {
		g.drawLine(xPos, yPos, xPos, 0);
		g.drawLine(xPos, yPos, getWidth(), yPos);
	}

	public void drawNums(Graphics g, int xPos, int yPos) {
		g.setFont(new Font("Courier", Font.ITALIC, 12));
		for (int i = MIN_ROLL; i <= MAX_ROLL; i++) {
			if (i < 10) {
				g.drawString("" + i, xPos + 24 * (i-4) + 13, yPos + 12);
			} else {
				g.drawString("" + i, xPos + 24 * (i-4) + 10, yPos + 12);
			}
		}
	}

	public void drawBars(Graphics g, int xPos, int yPos) {
		for (int i = MIN_ROLL; i <= MAX_ROLL; i++) {
			g.fillRect(xPos + 24 * (i-4) + 9, 
					yPos - 4000 * hm.get(i) / TRIALS,
					18, 4000 * hm.get(i) / TRIALS);
		}
	}

	public void mouseClicked(MouseEvent arg0) {
		histogram();
		repaint();
	}

	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}
}