/**
 * PieDistro.java, Pie Charts showing ration of fish species by Year for each lake version 0.1
 * Neil Moomey, www.neilmoomey.com/gis268/
 **/

// first import standard java packages that we will need
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.io.*;

//now import the main geotools package
import uk.ac.leeds.ccg.geotools.*;
//finaly import the toolbar from the widgets package
import uk.ac.leeds.ccg.widgets.*;

public class PieDistro extends Applet implements java.awt.event.ItemListener, uk.ac.leeds.ccg.geotools.ViewerClickedListener
{

	String shapefile = "maps/anchorage_lakes";
	String nameYear[] = {"2003","2004","2005","2006","2007"};
	String nameFish[] = {"RT","KS", "AC"};
	String niceName[] = {"Rainbow Trout", "Chinook Salmon", "Arctic Char"};
	Color color[] = {Color.decode("#FF0000"),Color.decode("#00FF00"),Color.decode("#0000FF")};
	String tooltip = "LAKE";

    //A Viewer is the component in which any maps are actualy displayed.
    Viewer view = new Viewer(); // Note it is declared and initalized here
    Panel pieKeys = new Panel(); //Panel to hold the pie chart key

	Panel pies, right, rightBottom;
	PieChart[] pie = new PieChart[nameYear.length];
	GeoData[] data = new GeoData[nameYear.length];
	GeoData tips;

    FirstPastPostShader fpps; //only used here as a quick way to build the key for the pie chart.
    //Future versions of charts should be able to produce their own keys.

    Theme t;
    GeoLabel place = new GeoLabel(); //Linked label to display current state name
    boolean loaded = false; //Have the maps been loaded yet?

    //Initalise the applets comonents and sort out the layout
    public void init(){
        System.out.println("Pie Applet Demo");
        //Switch to BorderLayout
        this.setBackground(Color.white);
        setLayout(new BorderLayout(10,10));
		view.addViewerClickedListener(this);
		add(view,"Center"); //Add the view to the center so that it will expand to fill available space

		//setup panels.
        rightBottom = new Panel();
        right = new Panel();
        right.setLayout(new GridLayout(4,1));
        pies = new Panel(new GridLayout(2,7));
		System.out.println("nameYear.length = " + nameYear.length);

		pies.add(new Label("Stocked Fish:  ", Label.RIGHT));  // Col 1, Row 1

		for(int i=0; i<nameYear.length; i++){
			pie[i] = new PieChart();
			pies.add(pie[i]);
		}

		// Add a spacer to make the Pie Charts taller
		Font f2 = new Font("Arial",Font.BOLD,38);
		Label spacer = new Label("");
		spacer.setFont(f2);
		pies.add(spacer);  // Col 1, Row 7

		// Next row
		pies.add(new Label("Year:  ", Label.RIGHT));  // Col 1, Row 2

		for(int i=0; i<nameYear.length; i++){
			pies.add(new Label("  " + nameYear[i]));
		}

		add(pies, "South");

        add(right,"East");
        rightBottom.setLayout(new BorderLayout());

        //Set up place label
        Font f = new Font("Arial",Font.BOLD,14);
        place.setFont(f);
        rightBottom.add(place,"South");

        // Add fish
		Image image = getImage(getDocumentBase(), "images/compass.gif");
		ImageIconAwt imageIconAwt = new ImageIconAwt(image);

		right.add(imageIconAwt);
		right.add(rightBottom);
        right.add(pieKeys);
        ScaleBar scaleBar = new ScaleBar(view);
        scaleBar.setUnits("-feet");
		right.add(scaleBar);
        //that's it for initalization, the rest will come when start() is called.
}

    public void start(){
        //load maps
        try{
            if(!loaded){
                loaded=true;
                loadMaps();
            }
        }
        catch(IOException e){
            this.showStatus("Error loading map file "+e);
        }
    }

    //Keep a note of which group was displayed last.
    public int last =0;

    public void loadMaps() throws IOException{

        //setup the shapefile reader as in past examples.
        //String shapefile = this.getParameter("shapefile"); //this should be a relative address.
        URL url = new URL(getCodeBase(),shapefile);
        ShapefileReader sfr = new ShapefileReader(url);
        //Grab the theme as normal
        t = sfr.getTheme();

        tips = sfr.readData(tooltip);

        //Find how many groups there are
		int groups = nameFish.length;
		MonoShader monoShader = new MonoShader(Color.decode("#A3C6FF"));
		t.setShader(monoShader);

        fpps = new FirstPastPostShader();//This shader is just being used to build a key.

        //loop through once for each group
		for(int i=0;i<nameYear.length;i++){
			for(int j=0;j<nameFish.length;j++){
				String name = nameFish[j] + nameYear[i];
				System.out.println("Adding "+name);
				data[i] = sfr.readData(name);//Grab the data
				data[i].setName(niceName[j]); // Set the name for the geodata to the one selected above
				if (i==0) fpps.addGroup(data[i],color[j]);
				//add the data to the pie
				pie[i].addGroup(data[i],color[j]);
			}
		}

        System.out.println("Setting up highlight manager");

        pieKeys.add(fpps.getKey());//pull the key from the shader, pies should be able to do this themselves.

        //Create a higlight manager
        HighlightManager hm = new HighlightManager();
        //pass it to the theme
        t.setHighlightManager(hm);

        String highlightHex = this.getParameter("highlightColor");//get optional highlight color
        ShadeStyle hs = t.getHighlightShadeStyle();
        Color hiColor = Color.pink;
        hs.setFillColor(hiColor);

        //add the pie component as a listener to the highlight manager
        for (int k=0; k<nameYear.length; k++) {
			hm.addHighlightChangedListener(pie[k]);
		}

        //set the tool tip data as the tip data for the theme
        t.setTipData(tips);

        place.setGeoData(tips);//Set the data for the label
        hm.addHighlightChangedListener(place);//Add the label as a highlight listener

       //add the theme to the viewer
        view.addTheme(t);
    }

		public void viewerClicked(ViewerClickedEvent vce){
		System.out.println("***ViewerClickedEvent");
	        GeoPoint p = vce.getLocation();
	        int id = t.getID(p); //get the postion of the click then the dbf matching value
			String lake = t.getTipText(id);
			// Replace the spaces with underscores.
			char c1 = ' ';
			char c2 = '_';
			String lake_url = lake.trim();  // Removes whitespace at both ends
			lake_url = lake_url.replace(c1,c2);

	        try {
					URL url = new URL ("http://www.neilmoomey.com/gis268/" + lake_url + ".htm");
	                AppletContext ac = getAppletContext();

	                if ( (lake_url.equals("Campbell_Point_Lake")) || (lake_url.equals("Cheney_Lake")) || (lake_url.equals("DeLong_Lake")) || (lake_url.equals("Jewel_Lake"))  || (lake_url.equals("Lake_Otis")) || (lake_url.equals("Sand_Lake")) || (lake_url.equals("Taku_Campbell_Lake")) || (lake_url.equals("University_Lake")) ) ac.showDocument(url,"clickDetails");

            } catch (Exception e) {System.err.println(e + "falling over");}
	}

    /**
     * Called when one of the group radio buttons has been selected.
     **/
    public void itemStateChanged(java.awt.event.ItemEvent ie){
		// Do nothing
    }
    /**
     * A Standard Applet method
     * @return String description of applet perameters.
     */
    public String getAppletInfo(){
        String info = "Anchorage Lakes, 5 Year Stock Plan by Neil Moomey, GIS 268 Project.";
        return info;
    }
}

