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

package org.jboss.media.registry;

import java.util.Iterator;
import java.util.Map;

import javax.emb.FormatAlreadyBoundException;
import javax.emb.MediaFormat;

/**
 * A reflection based implementation of a <code>MediaFormat</code> registry.
 *
 * <p>It allows to declare <code>MediaFormat</code> instances as class names.
 *
 * @version <tt>$Revision: 1.1 $</tt>
 * @author <a href="mailto:ricardoarguello@users.sourceforge.net">Ricardo Argüello</a>
 */
public class ReflectionMediaFormatRegistry extends SimpleMediaFormatRegistry
{
   public ReflectionMediaFormatRegistry()
   {
      super();
   }

   public ReflectionMediaFormatRegistry(Map initialEntries)
   {
      this();

      Iterator it = initialEntries.keySet().iterator();

      while (it.hasNext())
      {
         String fileExtension = (String) it.next();

         String mediaFormatClassName =
            (String) initialEntries.get(fileExtension);

         try
         {
            this.bind(fileExtension, mediaFormatClassName);
         }
         catch (FormatAlreadyBoundException ignore)
         {
         }
      }

   }

   public void bind(String fileExtension, String mediaFormatClassName)
      throws FormatAlreadyBoundException
   {
      try
      {
         Class mediaFormatClass = Class.forName(mediaFormatClassName);

         // FIXME: This won't work, since IIO MediaFormats have constructors 
         // with an ImageReader as parameter!
         MediaFormat mediaFormat = (MediaFormat) mediaFormatClass.newInstance();

         super.bind(fileExtension, mediaFormat);
      }
      catch (ClassNotFoundException e)
      {
         throw new IllegalArgumentException(e.getMessage());
      }
      catch (InstantiationException e)
      {
         throw new IllegalArgumentException(e.getMessage());
      }
      catch (IllegalAccessException e)
      {
         throw new IllegalArgumentException(e.getMessage());
      }
   }

   public void rebind(String fileExtension, String mediaFormatClassName)
   {
      try
      {
         Class mediaFormatClass = Class.forName(mediaFormatClassName);
         MediaFormat mediaFormat = (MediaFormat) mediaFormatClass.newInstance();
         super.rebind(fileExtension, mediaFormat);
      }
      catch (ClassNotFoundException e)
      {
         throw new IllegalArgumentException(e.getMessage());
      }
      catch (InstantiationException e)
      {
         throw new IllegalArgumentException(e.getMessage());
      }
      catch (IllegalAccessException e)
      {
         throw new IllegalArgumentException(e.getMessage());
      }
   }
}
