/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.media.engine.image;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Vector;

import javax.imageio.ImageIO;

import org.jboss.media.engine.MediaPluginGraph;
import org.jboss.media.engine.MediaPublisher;
import org.jboss.media.engine.MediaPublisherMBean;

/**
 * @version <tt>$Revision: 1.1 $</tt>
 * @author <a href="mailto:spyridon_samothrakis@yahoo.com">Spyridon Samothrakis</a>
 * @jmx.mbean extends="org.jboss.media.engine.MediaPublisherMBean"
 */
public class ImageFileMediaPublisher
   extends MediaPublisher
   implements MediaPublisherMBean, ImageFileMediaPublisherMBean
{
   MediaPluginGraph m_graph;

   public ImageFileMediaPublisher()
   {
      // DO NOTHING
   }

   /* (non-Javadoc)
    * @see org.jboss.media.engine.MediaPublisher#publish()
    */
   public void publish() throws Exception
   {
      log.info("Reading file " + getFileName());
      BufferedImage image = null;
      try
      {
         File imgFile = new File(getFileName());
         image = (BufferedImage) ImageIO.read(imgFile);
      }
      catch (IOException e)
      {
         log.error("Could not read file " + getFileName());
         return;
      }

      log.info("processing image...");
      processImage(image);
      log.info("Finished processing image");

      log.info("Sending the output to file " + getContext());
      File outputFile = new File(getContext());
      String suffix = getContext().substring(getContext().length()-3,getContext().length()); 
      log.info("Suffix is ." + suffix);
      ImageIO.write(image, suffix, outputFile);

   }

   /**
    * @param image
    * @return
    */
   private void processImage(BufferedImage image)
   {
      Vector plugins = m_graph.getPluginVector();
      for (Iterator iter = plugins.iterator(); iter.hasNext();)
      {
         ImagePluginSupport element = (ImagePluginSupport) iter.next();

         element.process(image);

      }

   }

   /* (non-Javadoc)
    * @see org.jboss.media.engine.MediaPublisher#stop()
    */
   public void stop()
   {

   }

   /* (non-Javadoc)
    * @see org.jboss.media.engine.MediaPublisher#addPluginGraph(org.jboss.media.engine.MediaPluginGraph)
    */
   public void addPluginGraph(MediaPluginGraph pg)
   {
      m_graph = pg;
   }

}
