/** JAISimpleViewer Class
   * @version 1.0  18 Jan 1999
   * @author Lawrence Rodrigues
   **/
package app;

import java.awt.*;
//import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import javax.swing.*;
import javax.media.jai.*;
import com.sun.media.jai.codec.*;
import com.vistech.util.*;

public class JAISimpleViewer1 extends ApplicationFrame{
   protected ImagePanel viewer;

   public static void  main(String[] args){
      JAISimpleViewer1 ip = new JAISimpleViewer1();
      if(args.length <1) {
        System.out.println("Enter a valid image file name");
        System.exit(0);
      }
      ip.loadAndDisplay(args[0]);
   }

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

   public PlanarImage readAsPlanarImage(String filename) {
      Image img = readImage(filename);
      return JAI.create("awtimage", img);
   }

   public Image readImage(String imageName){
      Image image = Toolkit.getDefaultToolkit().getImage(imageName);
      MediaTracker imageTracker = new MediaTracker(this);
      imageTracker.addImage(image, 0);
      try{
        imageTracker.waitForID(0);
      }catch(InterruptedException e){ return null;}
      return image;
   }

   public void loadAndDisplay(String filename){
      PlanarImage img = readAsPlanarImage(filename);
      displayImage(img);
   }

   public void displayImage(PlanarImage img) {
      int width = img.getWidth();
      int height = img.getHeight();
      Dimension d = ApplicationFrame.getViewerSize(width/(double)height);
      launchFrame(img, d.width, d.height);
   }

   public void launchFrame(PlanarImage img, int width, int height) {
      setTitle("JAI Image Viewer");
      viewer = new ImagePanel(img);
      viewer.setPreferredSize(new Dimension(width, height));
      Container cp = getContentPane();
      getContentPane().setLayout(new GridLayout(1,1));
      cp.add(viewer);
      pack();
      setSize(new Dimension(width, height));
      show();
      viewer.repaint();
   }

   protected class ImagePanel extends JComponent {
      protected PlanarImage image;
      protected AffineTransform atx = new AffineTransform();
      protected int width, height;
      public ImagePanel(){}
      public ImagePanel(PlanarImage img){
         image = img;
         width = img.getWidth();
         height = img.getHeight();
      }

      public void paintComponent(Graphics gc){
         Graphics2D g = (Graphics2D)gc;
         Rectangle rect = this.getBounds();
         if((width != rect.width) || (height != rect.height)){
             double magx = rect.width/(double)width ;
             double magy = rect.height/(double)height ;
             atx.setToScale(magx, magy);
         }
         if(image != null) g.drawRenderedImage(image, atx);
      }
   }
}
