//
//  Classify.java
//  Classify
//
//  Created by Morgan Conbere on 11/10/06.
//
//  Feel free to use and distribute this code at will.
//  I am not responsible for any damage or loss of
//  productivity associate with the use or misuse of
//  this product.
//

import java.awt.*;
import java.applet.*;

import java.awt.event.*;
import java.net.*;
import java.io.*;


//
//  The main Applet extending class
//
public class Classify extends Applet implements ActionListener, MouseListener {

	static boolean DEBUG = false;
	
	//  General Applet information
	int width, height;
	URL base;
	
	//  Applet GUI Global Variables
    Button backButton;
    Button nextButton;
    Button submitButton;

	Checkbox lizardYesBox;
	Checkbox lizardNoBox;

	// Initialization of the Applet
	public void init() {
		if (DEBUG) System.out.println("Applet initializing!");
		width = getSize().width;
		height = getSize().height;
		try {
			base = getDocumentBase();
			if (DEBUG) System.out.println("Success: got document base");
		} catch (Exception e) {
			System.out.println("Error: base not detected");
		}

		System.out.println("Trying to list all of the images in the directory");
		
		try {
			URL imagesURL = new URL(base, "images/images.txt");
			BufferedReader in = new BufferedReader(new InputStreamReader(imagesURL.openStream()));
				
			int numImages = Integer.parseInt(in.readLine());
			System.out.println("Got num images: " + numImages);
			
			lizardListing = new String[numImages];
			for (int i = 0; i < numImages; i++) {
				lizardListing[i] = in.readLine();
				if (DEBUG) System.out.println("file: " + lizardListing[i]);
			}
		} catch (Exception e) {
			System.out.println("No beans, no images listed!");
			System.exit(1);
		}
		
		System.out.println("Done");
		
		// Initialize the lizard image
		lizardListingIndex = 0;
		newImage();
		
		//  The layout is arranged simply as a flowlayout
		setLayout(new FlowLayout());        //  The main layout
    
		backButton = new Button("Back");
		nextButton = new Button("Next");
		add(backButton);
		add(nextButton);
		
		add(new Label("Add data to database:"));
		submitButton = new Button("Submit");
		add(submitButton);
		
		//  Listen to the buttons
		backButton.addActionListener(this);
		nextButton.addActionListener(this);
		submitButton.addActionListener(this);		

		addMouseListener(this);
	}
	
	public void getLizardImage() {
		Image result;
		try {
			if (DEBUG) System.out.println("Log: base is: " + base);
			result = getImage(base, "images/" + lizardListing[lizardListingIndex]);
			if (DEBUG) System.out.println("Success: Got image: " + lizardListing[lizardListingIndex]);
		} catch (Exception e) {
			System.out.println("Error: Image: " + lizardListing[lizardListingIndex] + "does not exist");
			result = null;
		}
		lizard = result;
		repaint();
	}
	
	//  Handle button clicks
	public void actionPerformed(ActionEvent event) {
		if (event.getSource() == backButton) {
			if (DEBUG) System.out.println("Log: Back button clicked");
			backImage();
		} else if (event.getSource() == nextButton) {
			if (DEBUG) System.out.println("Log: Next button clicked");
			nextImage();
		} else if (event.getSource() == submitButton) {
			if (DEBUG) System.out.println("Log: Submit button clicked");
			submit();
		}
	}

	
	//////////////////////////////
	//       LIZARD TOOLS       //
	//////////////////////////////
	
	// Lizard information
	Image lizard;
	String[] lizardListing;
	int lizardListingIndex;
	int x, y;
	boolean exists;
		
	// Image Display Information
	static int dispX = 50;
	static int dispY = 50;
	static int dispWidth = 300;
	static int dispHeight = 300;
	

	//  Image loading functions
	public void backImage() {
		if (lizardListingIndex > 0) {
			lizardListingIndex--;
			newImage();
		}
	}
	
	public void nextImage() {
		if (lizardListing.length - 1 > lizardListingIndex) {
			lizardListingIndex++;
			newImage();
		}
	}
	
	public void newImage() {
		x = 0;
		y = 0;
		setExists(false);
		
		getLizardImage();
	}
	
	public void setExists(boolean b) {
		exists = b;
	}

	
	//  Drawing functions
	public void paint(Graphics g) {
		g.drawImage(lizard, dispX, dispY, dispWidth, dispHeight, this);
		if (exists) {
			g.setColor(new Color(160,0,0,240));
			g.fillOval(x-2, y-2, 4, 4);
		}
		g.drawString("image: "+lizardListing[lizardListingIndex],50,365);
	}
	
	//  MouseListening
	public void mouseReleased(MouseEvent event) {
		int tx = event.getX();
		int ty = event.getY();
		
		if (DEBUG) System.out.println("Log: saw mouse click at (" + tx + "," + ty + ")");
		
		if (tx >= dispX && tx < (dispX + dispWidth) &&
			ty >= dispY && ty < (dispY + dispHeight) ) {
			x = tx;
			y = ty;
			setExists(true);
		}

		repaint();
	}
	
	//  Submitting to website
	public void submit() {
		if (exists) try {
			int lizardWidth = lizard.getWidth(null);
			int lizardHeight= lizard.getHeight(null);

			if (DEBUG) System.out.println("lizardWidth: "+lizardWidth+"  dispWidth: "+dispWidth+"  x: "+x);

			int imageX = (int)((x - dispX) * ((double)lizardWidth / dispWidth));
			int imageY = (int)((y - dispY) * ((double)lizardHeight / dispHeight));
		
			if (DEBUG) System.out.println("lizard " + imageX + " " + imageY);

			String urlString = "cgi-bin/lizardinput.cgi" +
				"?filename=" + lizardListing[lizardListingIndex] +
				"&x=" + imageX +
				"&y=" + imageY;
			
			if (DEBUG) System.out.println("making URL: " + urlString);
			URL url = new URL(getDocumentBase(), urlString);
			if (DEBUG) System.out.println("making connection");
			BufferedInputStream buffer = new BufferedInputStream(url.openStream());
			BufferedReader in = new BufferedReader(new InputStreamReader(buffer));
			String line;
			while((line=in.readLine()) != null) {
				System.out.println(line);
			}
			if (DEBUG) System.out.println("Log: sent data to server");
		} catch (MalformedURLException e) {
			System.out.println("GET failed: bad URL");
		} catch (IOException e) {
			System.out.println("GET failed: openConnection failed"); 
		}
		setExists(false);

	}
	
	//  Required functions for MouseListener
	public void mouseClicked(MouseEvent e) {}
	public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    //public void mouseReleased(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}	
}
