package edu.uky.ai.ml;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JPanel;

/**
 * A 5x7 array of toggelable pixels that allows the user to draw an image
 * which the neural network will attempts to classify.
 * 
 * @author Stephen G. Ware
 */
public class AlphabetInputPanel extends JPanel {

	/** Version 1.0 */
	private static final long serialVersionUID = 1L;
	
	/** The parent frame to which this panel belongs */
	public final AlphabetFrame frame;
	
	/** A map of the state of each pixel */
	private boolean[] input = new boolean[5 * 7];
	
	/**
	 * Constructs a new input panel.
	 * 
	 * @param frame the parent frame to which this panel belongs
	 */
	public AlphabetInputPanel(AlphabetFrame frame) {
		this.frame = frame;
		addMouseListener(mouseListener);
	}
	
	@Override
	public void paintComponent(Graphics g) {
		Graphics2D g2d = (Graphics2D) g;
		g2d.setColor(Color.WHITE);
		g2d.fillRect(0, 0, getWidth(), getHeight());
		g2d.setColor(Color.BLACK);
		int w = getWidth() / 5;
		int h = getHeight() / 7;
		for(int x=0; x<5; x++) {
			for(int y=0; y<7; y++) {
				if(input[y * 5 + x])
					g2d.fillRect(x * w, y * h, w, h);
			}
		}
	}
	
	/**
	 * Returns an array of double values suitable for input to the neural
	 * network based on the current state of the image.
	 * 
	 * @return an input vector
	 */
	private double[] getInput() {
		double[] in = new double[5 * 7];
		for(int i=0; i<input.length; i++)
			in[i] = input[i] ? 1 : 0;
		return in;
	}

	/** Handles mouse clicks */
	private final MouseListener mouseListener = new MouseAdapter() {
		
		@Override
		public void mouseClicked(MouseEvent event) {
			int x = event.getX() * 5 / getWidth();
			int y = event.getY() * 7 / getHeight();
			input[y * 5 + x] = !input[y * 5 + x];
			frame.output.setText("Looks like \"" + frame.network.classify(frame.database, getInput()) + "\"");
			frame.repaint();
		}
	};
}
