/* Author: Clauirton Siebra <c.siebra@ed.ac.uk>
 * Updated: Fri Sep 23 12:45:50 2003 by Clauirton Siebra
 * Copyright: (c) 2003, AIAI, University of Edinburgh
 */

package ix.ip2.map;

import com.bbn.openmap.omGraphics.*;
import com.bbn.openmap.proj.Projection;
import com.bbn.openmap.proj.Proj;
import com.bbn.openmap.plugin.OMGraphicHandlerPlugIn;
import com.bbn.openmap.LatLonPoint;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.*;
import javax.swing.ImageIcon;
import ix.util.Util;

/**
 * Class that creates a new laywer that enables the manipulation of JPG images. This layer understands the following additional properties:<p>
 *      jpgPath = path to the JPG file that will be loaded by the layer; <p>
 *      latLeftSuperior = latitude of the left superior corner of the JPG image. Default is 0;
 *      lonLeftSuperior = longitude of the left superior corner of the JPG image. Default is 0;
 *      latRightInferior = latitude of the right inferior corner of the JPG image. Default is 0;
 *      lonRightInferior = longitude of the right inferior corner of the JPG image. Default is 0;
 */

public class JpgMapLayer extends OMGraphicHandlerPlugIn {

    HashSet tiles = new HashSet();
    private float latLeftSup,latRightInf;
    private float lonLeftSup,lonRightInf;
    private String jpgPath = null;
    private Image image = null;
    private boolean calcule = false;

    /**
     * Default layer constructor.
     */
    public JpgMapLayer() {
        super();
    }

    /**
     * Implements the abstract getRectangle method of the AbstractPlugIn class.  
     */
    public OMGraphicList getRectangle(Projection p) {
        OMGraphicList list = (OMGraphicList)getList();
        list.clear();
        if (image == null) {
	    loadMap(p);
        }
        
        Iterator it = tiles.iterator();
        while (it.hasNext()) {
            OMScalingRaster tile = (OMScalingRaster) it.next();
            if (tile.isOnMap(p)) {
		tile.generate(p);
                list.add(tile);
	    }
        }
        repaint();
        return list;
    }

    /**
     * Sets the properties related to this layer. This method can be extended to support any other property. The current properties are:<p>
     *   <li> jpgmaplayer.class
     *   <li> jpgmaplayer.prettyName
     *   <li> jpgmaplayer.plugin
     *   <li> jpgmaplayer.jpgPath
     *   <li> jpgmaplayer.latLeftSuperior
     *   <li> jpgmaplayer.lonLeftSuperior
     *   <li> jpgmaplayer.latRightInferior
     *   <li> jpgmaplayer.lonRightInferior
     */
    public void setProperties(String prefix, Properties props) {
        // Let the Layer process the basic layer properties
        super.setProperties(prefix, props);
        // now do my stuff
        prefix = prefix.substring(0,prefix.indexOf("."));
        jpgPath = props.getProperty(prefix + ".jpgPath", "defaultPath");

	if( (props.getProperty(prefix + ".selfSetting", "false").equals("true")) ) {
	    calcule = true;
	}
	else {
	    latLeftSup = Float.parseFloat(props.getProperty(prefix + ".latLeftSuperior", "0.0f"));
	    lonLeftSup = Float.parseFloat(props.getProperty(prefix + ".lonLeftSuperior", "0.0f"));
	    latRightInf = Float.parseFloat(props.getProperty(prefix + ".latRightInferior", "0.0f"));
	    lonRightInf = Float.parseFloat(props.getProperty(prefix + ".lonRightInferior", "0.0f"));
	    // ...

	    String error = "";
	    if(latLeftSup<latRightInf)
		error = error+"- The parameter latLefSup needs to be norther than latRightInf. \n";
	    if(lonLeftSup>lonRightInf)
		error = error+"- The parameter lonRightInf needs to be easter than lonLeftSup. \n";
	    if(!error.equals("")) {
		error = "Errors in file map.props: \n"+error;
		error = error+"Generate automatic parameters?";
		if(Util.dialogConfirms(null,error))
		    calcule = true;
		else
		    System.exit(0);
	    }
	}

    }

    /**
     * Loads the jpg image whose path is specified in the .props file.  
     */
    protected void loadMap(Projection p) {
        int imageCount = 0;
        if (jpgPath != null) {
            MediaTracker tracker = new MediaTracker(component); // Create a media tracker        
	    ImageIcon ii = new ImageIcon(jpgPath);
            image= ii.getImage();
            try {
                tracker.addImage(image, imageCount);
                tracker.waitForID(imageCount); 
            } catch (Exception e) {} // Catch errors
	    if(calcule)
		calculateImageParameters(p,ii);
            OMScalingRaster omsr = new OMScalingRaster(latLeftSup,lonLeftSup,latRightInf,lonRightInf,image);
            tiles.add(omsr);
            imageCount++;
        }
    }

    protected void calculateImageParameters(Projection proj,ImageIcon ii) {

	Point pCenter = proj.forward(proj.getCenter());

	LatLonPoint ls = proj.inverse(pCenter.x - ii.getIconWidth()/2,pCenter.y - ii.getIconHeight()/2);
	LatLonPoint ri = proj.inverse(pCenter.x + ii.getIconWidth()/2,pCenter.y + ii.getIconHeight()/2);

	latLeftSup = ls.getLatitude(); 
	lonLeftSup = ls.getLongitude();
        latRightInf = ri.getLatitude();
        lonRightInf = ri.getLongitude();

	System.out.println("New parameters: latLeftSuperior("+latLeftSup+") lonLeftSuperior("+lonLeftSup+") latRightInferior("+latRightInf+") lonRightInferior("+lonRightInf+")");

	//Util.displayAndWait(null,"The new parameters are:");

    }
}

