/*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
package org.jboss.annotation.factory;

import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.Map;

import org.jboss.beans.info.spi.BeanInfo;
import org.jboss.config.plugins.property.PropertyConfiguration;
import org.jboss.config.spi.Configuration;
import org.jboss.util.JBossObject;
import org.jboss.util.Objects;

/**
 * InvocationHandler implementation for creating an annotation proxy.
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @author <a href="mailto:kabir.khan@jboss.org">Kabir Khan</a>
 * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
 */
public class AnnotationProxy implements InvocationHandler, Serializable
{
   private static final long serialVersionUID = 1;
   private static Configuration configuration;

   static
   {
      configuration = AccessController.doPrivileged(new PrivilegedAction<Configuration>()
      {
         public Configuration run()
         {
            return new PropertyConfiguration();
         }
      });
   }

   private Class<?> annotationType;
   private transient BeanInfo beanInfo;
   private Map<String, Object> map;

   @SuppressWarnings("unchecked")
   public AnnotationProxy(Class<?> annotationType, Map valueMap)
   {
      if (annotationType == null)
         throw new IllegalArgumentException("Null annotation type.");
      this.annotationType = annotationType;
      this.map = valueMap != null ? valueMap : Collections.<String, Object>emptyMap();
   }

   /**
    * Get bean info.
    *
    * @return the annotation's bean info
    */
   protected BeanInfo getBeanInfo()
   {
      if (beanInfo == null)
         beanInfo = configuration.getBeanInfo(annotationType);

      return beanInfo;
   }

   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
   {
      String name = method.getName();
      if ("equals".equals(name))
      {
         return doEquals(proxy, args[0]);
      }
      else if ("hashCode".equals(name))
      {
         return doHashCode();
      }
      else if ("toString".equals(name))
      {
         return map.toString();
      }
      else if ("annotationType".equals(name))
      {
         return annotationType;
      }
      return map.get(name);
   }

   public Object getValue(String name)
   {
      return map.get(name);
   }

   @SuppressWarnings("unchecked")
   private Object doEquals(Object proxy, Object obj)
   {
      if (obj == proxy)
         return Boolean.TRUE;
      if (obj == null)
         return Boolean.FALSE;

      if (annotationType.isInstance(obj) == false)
      {
         return Boolean.FALSE;
      }

      try
      {
         for (String key : map.keySet())
         {
            Object value = getValue(key);
            Object other = getBeanInfo().getProperty(obj, key);
            if (Objects.isArray(value))
            {
               if (Objects.isArray(other) == false)
                  return Boolean.FALSE;

               int length = Array.getLength(value);
               if (length != Array.getLength(other))
                  return Boolean.FALSE;

               for (int i = 0; i < length; i++)
               {
                  if (JBossObject.equals(Array.get(value, i), Array.get(other, i)) == false)
                     return Boolean.FALSE;
               }
            }
            else if (JBossObject.equals(value, other) == false)
               return Boolean.FALSE;
         }
      }
      catch (Throwable t)
      {
         throw new UndeclaredThrowableException(t);
      }

      return Boolean.TRUE;
   }

   private Object doHashCode()
   {
      return map.hashCode();
   }

   /**
    * Create a proxy implementation for the annotation class.
    * @param map - map of the annotation values
    * @param annotation - the annotation class
    * @return an instance implementing the annotation
    * @throws Exception for any error
    */
   public static Object createProxy(Map<String, Object> map, Class<?> annotation) throws Exception
   {
      AnnotationProxy proxyHandler = new AnnotationProxy(annotation, map);
      return java.lang.reflect.Proxy.newProxyInstance(annotation.getClassLoader(), new Class[]{annotation}, proxyHandler);
   }
}
