/*
 * JBoss, the OpenSource J2EE webOS
 * 
 * Distributable under LGPL license. See terms of license at gnu.org.
 */

package org.jboss.media.format.image.iio;

import java.io.IOException;
import java.io.InputStream;
import java.rmi.RemoteException;

import javax.emb.MediaException;
import javax.emb.MediaHeader;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.FileCacheImageInputStream;
import javax.imageio.stream.ImageInputStream;

import org.jboss.media.format.EmbeddedMediaFormat;

/**
 * Implementation of the <code>MediaFormat</code> interface based on the Java
 * Image I/O API to be used on embedded media.
 * 
 * @version <tt>$Revision: 1.3 $</tt>
 * @author <a href="mailto:ricardoarguello@users.sourceforge.net">Ricardo
 *         Argüello</a>
 */
public abstract class IIOMediaFormat extends EmbeddedMediaFormat
{
   protected ImageReader imageReader;

   /**
    * Constructor.
    * 
    * @param imageReader
    */
   public IIOMediaFormat(ImageReader imageReader)
   {
      super();
      this.imageReader = imageReader;
   }

   /**
    * @see javax.emb.MediaFormat#extractHeader(javax.emb.Media)
    */
   public abstract MediaHeader extractHeader(InputStream content)
      throws MediaException;

   /**
    * @see javax.emb.MediaFormat#getDefaultMimeType()
    */
   public String getDefaultMimeType()
   
   {
      try
      {
         // FIXME: This is wrong!
         return "image/" + imageReader.getFormatName();
      } catch (IOException e)
      {
         // ignore?
         return null;
      }
   }

   /**
    * @see javax.emb.MediaFormat#isStreamingDesirable()
    */
   public boolean isStreamingDesirable()
   {
      return false;
   }

   protected IIOMetadata extractImageMetadata(InputStream content)
      throws MediaException
   {
      ImageInputStream imageInputStream = null;

      try
      {
         imageInputStream = new FileCacheImageInputStream(content, null);

         imageReader.setInput(imageInputStream);
         IIOMetadata imageMetadata = imageReader.getImageMetadata(0);

         return imageMetadata;
      } catch (RemoteException re)
      {
         throw new RuntimeException(re.getMessage());
      } catch (IOException ioe)
      {
         throw new MediaException(ioe.getMessage());
      } finally
      {
         try
         {
            imageInputStream.close();
            content.close();
         } catch (IOException ignore)
         {
         }
      }
   }
}