/** ImageLoaderJAI Class
   * @version 1.0  3 sept 2000
   * @author Lawrence Rodrigues
   **/
package com.vistech.jai.imageio;

import java.io.*;
import java.util.*;
import java.beans.*;
import java.awt.*;
import java.awt.image.*;
import javax.media.jai.*;
import com.sun.media.jai.codec.*;
import com.vistech.events.*;

/** Loads an image from a local directory using the JAI Image I/O package.Once an
  * image is loaded, it fires the imageLoaded event to the registered listeners.
  *
  * @version 1.0  3 Sept 2000
  * @author Lawrence Rodrigues
  */
public class ImageLoaderJAI implements ListSelectListener{
   protected PlanarImage loadedImage = null;
   protected PropertyChangeSupport pcNotifier;
   private Vector imgLst = new Vector();

   public ImageLoaderJAI() {
      pcNotifier= new PropertyChangeSupport(this);
   }
   public void load(ListSelectEvent e){
      File currentDir = e.getPath();
      String[] flist = e.getFileList();
      String path =
      (currentDir !=null)? currentDir.toString()+File.separator+flist[0]:flist[0];
      if(flist != null) loadImage(path);
   }

   public PlanarImage loadImage(String path) {
      PlanarImage img= readAsPlanarImage(path);
      fireImageLoadedEvent(img);
      return img;
   }

   public static PlanarImage readAsPlanarImage(String filename) {
      return JAI.create("fileload", filename);
   }

   public void setLoadedImage(PlanarImage img){
      pcNotifier.firePropertyChange("loadedImage",
                                     this.loadedImage,
                                     img);
      loadedImage = img;
   }

   public PlanarImage getLoadedImage(){
      return loadedImage;
   }

   public void addPlanarImageLoadedListener(PlanarImageLoadedListener il){
       imgLst.addElement(il);
   }
   public void removePlanarImageLoadedListener(PlanarImageLoadedListener il){
      if(!(imgLst.isEmpty())) imgLst.removeElement(il);
   }
   protected void fireImageLoadedEvent(PlanarImage img) {
      for(Enumeration e= imgLst.elements(); e.hasMoreElements();){
          PlanarImageLoadedEvent ie = new PlanarImageLoadedEvent(this, img);
          PlanarImageLoadedListener il = (PlanarImageLoadedListener)(e.nextElement());
          il.imageLoaded(ie);
      }
      setLoadedImage(img);
   }
}
