/**
 * StockingDensity.java, Stocking Density of fish in Anchorage Lakes using Quantile Shader, 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 StockingDensity extends Applet implements java.awt.event.ItemListener, uk.ac.leeds.ccg.geotools.ViewerClickedListener
{
	// Change these variables to update Applet with future data
	String shapefile = "maps/anchorage_lakes"; //this should be a relative address.
	String tooltip = "LAKE"; //this should be the name of a column in the dbf file
	String nameYear[] = {"2003","2004","2005","2006","2007"};
	String nameFish[] = {"RT","KS", "AC"};
	String niceName[] = {"Rainbow Trout", "Chinook Salmon", "Arctic Char"};

	// declare more global variables
	private Panel left, leftBottom, right, rightBottom, rightTop, mapKeys, pieKeys, radioYear, radioFish;

    Checkbox[] radiosYear; // radio buttons
	Checkbox[] radiosFish; // radio buttons
	CheckboxGroup year;  // The group containing all years
	CheckboxGroup fish;	 // The group containing all fish

    //Future versions of charts should be able to produce their own keys.
    GeoData[] groupData; // The values for each group
	GeoData data;  // data in ArcView Shapfile format

    Key[] groupKeys; // Key for each groups mapKeys
    ClassificationShader[] groupShader; //Shader for each group
    Theme t;  // Shapefile theme
    GeoLabel place;
	ToolBar tools;
    Viewer view;  // The map viewer
    boolean loaded = false; //Have the maps been loaded yet?
	ShapefileReader sfr;

	Image image;
	ImageIconAwt imageIconAwt;

    //Initalise the applets comonents and sort out the layout
    public void init(){
        System.out.println("***Anchorage Stocked Lakes by Neil Moomey");

        //setup panels.
		left = new Panel();  //Left half of screen to be placed in CENTER to hold the Map and toolbar
        right = new Panel(); //Right half of screen to hold everything else
        rightTop = new Panel();
        rightBottom = new Panel();
		mapKeys = new Panel(); //Panel to hold the map keys (Shader)
		radioYear = new Panel(); //Panel to hold radio button for the year group
		radioFish = new Panel(); //Panel to hold radio button for the fish group
		place = new GeoLabel(); //Linked label to display current state name
		view = new Viewer(); //Viewer is the map Panel.
		view.addViewerClickedListener(this);
        this.setBackground(Color.white);
		leftBottom = new Panel();


		// Add fish
		image = getImage(getDocumentBase(), "images/fish.gif");
		imageIconAwt = new ImageIconAwt(image);

		//Set all layout managers
		setLayout(new BorderLayout());
		left.setLayout(new BorderLayout());
		right.setLayout(new GridLayout(4,1));
		radioYear.setLayout(new GridLayout(nameYear.length,1));
		radioFish.setLayout(new GridLayout(nameFish.length,1));
		leftBottom.setLayout(new GridLayout(1,5));

        // Add all panels to panels
		left.add(view,"Center"); //Add the view to the center so that it will expand to fill available space
		leftBottom.add(new Label("")); // Spacer
		leftBottom.add(new Label("")); // Spacer
		ScaleBar scaleBar = new ScaleBar(view);
		scaleBar.setUnits("-feet");
		leftBottom.add(scaleBar);
		leftBottom.add(new Label("")); // Spacer

		left.add(leftBottom,"South");
		rightTop.add(radioYear);
		rightTop.add(radioFish);
		right.add(rightTop);	// Col 1
		right.add(imageIconAwt);

		rightBottom.add(mapKeys);//Add the key panel (which will have a key added to it latter)
		right.add(rightBottom); // Col 3


		// Add all panels to Applet Frame
		add(left, BorderLayout.CENTER);
		add(right, BorderLayout.EAST);

        //Set up place label
        Font f = new Font("Arial",Font.BOLD,14);
        place.setFont(f);
        right.add(place);
}

    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 int last_j = 0;

    public void loadMaps() throws IOException{
		String name, nicerName;

        //setup the shapefile reader
        URL url = new URL(getCodeBase(),shapefile);
        sfr = new ShapefileReader(url);

        //Grab the theme as normal
        t = sfr.getTheme();

        //setup tooltips
        GeoData tips = sfr.readData(tooltip);

        //Find how many groups there are
        int groups = nameYear.length * nameFish.length;
        System.out.println("***groups = " + groups);

        groupShader = new ClassificationShader[groups];//An array of mapKeys, one for each group
        groupData = new GeoData[groups];//An array of geodatas, one for each group

        year = new CheckboxGroup();//Group for all year checkboxes
		fish = new CheckboxGroup();//Group for all fish checkboxes

        radiosYear = new Checkbox[nameYear.length];
		radiosFish = new Checkbox[nameFish.length];

        groupKeys = new Key[groups];

	    //loop through once for each group
		int g=0; // counter
		for(int i=0;i<nameYear.length;i++) {
			for(int j=0;j<nameFish.length;j++) {
				name = nameFish[j] + nameYear[i];//The column in the dbf file for this group
				nicerName = nameYear[i]+" "+niceName[j];
				System.out.println("***Adding name "+name);
				data = sfr.readData(name);//Grab the data
				data.setName(nicerName); // Set the name for the geodata to the one selected above

				if (j==0) {
					radiosYear[i] = new Checkbox(nameYear[i],false,year);
					radiosYear[i].addItemListener(this);//Listen to it
					radioYear.add(radiosYear[i]);// add radio to panel
					System.out.println("***Adding radioYear["+i+"]");
				}
				if (i==0) {
					radiosFish[j] = new Checkbox(niceName[j],false,fish);
					radiosFish[j].addItemListener(this);//Listen to it
					radioFish.add(radiosFish[j]);// add radio to panel
					System.out.println("***Adding radioFish["+j+"]");
				}
				System.out.println("***g = "+ g);

            	System.out.println("Building mapKeys for "+nicerName);
				//Build a mapKeys, this one has 6 classifications split by equal intervals.
				groupShader[g] = new ClassificationShader(data, 6,ClassificationShader.EQUAL_INTERVAL,Color.white.brighter().brighter(),Color.red);
				groupData[g] = data;
				groupKeys[g] = groupShader[g].getKey();//get the key for that groups mapKeys
				g++;
			}
		}

        radiosYear[0].setState(true);//Set the first group as active
		radiosFish[0].setState(true);//Set the first group as active

        mapKeys.add(new Label("Fish/Acre-Ft"));
		System.out.println("***Setting up highlight manager");
        mapKeys.add(groupKeys[0]);

        //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);

        System.out.println("***Setting mapKeys");
        t.setShader(groupShader[1]);//set the theme up with the first mapKeys and data pair.
        t.setGeoData(groupData[1]);

        //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);
    }

    /**
     * Called when one of the group radio buttons has been selected.
     **/
    public void itemStateChanged(java.awt.event.ItemEvent ie){
		String cat;
		int g = 0;  // counter
        //Which group was chosen.
        Checkbox src = (Checkbox)ie.getSource();
        for(int i=0;i<radiosYear.length;i++){
        for(int j=0;j<radiosFish.length;j++){
            if(radiosYear[i] == src || radiosFish[j] == src){
                //group found
                t.setShader(groupShader[g]);//Switch to the mapKeys for that group
                t.setGeoData(groupData[g]);//Switch to the data for that group

                //Swap the keys over in the key panel
                mapKeys.add(groupKeys[g]);
                mapKeys.remove(groupKeys[last]);

                //Small fudge to get the keys to be the right size
                groupKeys[g].setSize(groupKeys[last].getSize());
                groupKeys[g].setLocation(groupKeys[last].getLocation());
                groupKeys[g].addNotify();
                last = g;

                groupKeys[g].doLayout();

                right.doLayout();
                repaint();
                return;//finished
            }
			g++;
        }
		}
    }


		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");}
	}

    /**
     * A Standard Applet method
     * @return String description of applet perameters.
     */
    public String getAppletInfo(){
        String info = "Anchorage Stocked Lakes Applet";
        return info;
    }

}

