/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2008, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file 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.weld.integration.deployer.jndi;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.jboss.beans.metadata.api.annotations.Inject;
import org.jboss.beans.metadata.api.model.FromContext;
import org.jboss.beans.metadata.spi.BeanMetaData;
import org.jboss.beans.metadata.spi.builder.BeanMetaDataBuilder;
import org.jboss.beans.metadata.spi.builder.ParameterMetaDataBuilder;
import org.jboss.dependency.spi.ControllerState;
import org.jboss.deployers.spi.DeploymentException;
import org.jboss.deployers.spi.deployer.DeploymentStages;
import org.jboss.deployers.spi.deployer.helpers.AbstractDeployer;
import org.jboss.deployers.structure.spi.DeploymentUnit;
import org.jboss.util.naming.NonSerializableFactory;
import org.jboss.weld.integration.deployer.DeployersUtils;

/**
 * Extract binding logic to an abstract binder deployer.
 *
 * @param <T> exact bootstrap bean
 * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
 */
public abstract class AbstractJndiBinderDeployer<T> extends AbstractDeployer
{
   public static final String BEAN_MANAGER_JNDI_SUBCONTEXT = "BeanManagers";

   private Class<T> bootstrapClass;
   private Object thisName;
   private Hashtable<String, String> jndiEnvironment = new Hashtable<String, String>();
   private Context beanManagerContext;

   protected AbstractJndiBinderDeployer(Class<T> bootstrapClass)
   {
      if (bootstrapClass == null)
         throw new IllegalArgumentException("Null bootstrap class");

      setTopLevelOnly(true);
      addInput(BeanMetaData.class);
      setStage(DeploymentStages.PRE_REAL);

      this.bootstrapClass = bootstrapClass;
   }

   public void deploy(DeploymentUnit unit) throws DeploymentException
   {
      String bootstrapName = DeployersUtils.getBootstrapBeanName(unit);
      String bbAttachmentName = bootstrapName + "_" + BeanMetaData.class.getSimpleName();

      BeanMetaData bbBMD = unit.getAttachment(bbAttachmentName, BeanMetaData.class);
      if (bbBMD != null)
      {
         BeanMetaDataBuilder builder = BeanMetaDataBuilder.createBuilder(bbBMD);

         ParameterMetaDataBuilder pmdb = builder.addInstallWithParameters("bind", thisName.toString(), ControllerState.INSTALLED, ControllerState.INSTALLED);
         pmdb.addParameterMetaData(bootstrapClass.getName(), builder.createThis());
         pmdb.addParameterMetaData(String.class.getName(), unit.getSimpleName());

         pmdb = builder.addUninstallWithParameters("unbind", thisName.toString(), ControllerState.INSTALLED, ControllerState.INSTALLED);
         pmdb.addParameterMetaData(bootstrapClass.getName(), builder.createThis());
         pmdb.addParameterMetaData(String.class.getName(), unit.getSimpleName());
      }
   }

   @Inject(fromContext = FromContext.NAME)
   public void setThisName(Object thisName)
   {
      this.thisName = thisName;
   }

   protected Context createContext() throws NamingException
   {
      return new InitialContext(jndiEnvironment);
   }

   public void create() throws Exception
   {
      if (jndiEnvironment != null)
         addNonSerializableFactory(jndiEnvironment); // is here OK?

      Context context = createContext();
      beanManagerContext = context.createSubcontext(BEAN_MANAGER_JNDI_SUBCONTEXT);
   }

   protected Context getBeanManagerContext()
   {
      return beanManagerContext;
   }

   public void destroy()
   {
      try
      {
         Context context = createContext();
         context.destroySubcontext(BEAN_MANAGER_JNDI_SUBCONTEXT);
      }
      catch (Exception ignore)
      {
      }
   }

   public void setJndiEnvironment(Hashtable<String, String> jndiEnvironment)
   {
      this.jndiEnvironment = jndiEnvironment;
   }

// --- binding logic ---

   public abstract void bind(T bootstrapBean, String deploymentUnitName) throws NamingException;

   public abstract void unbind(T bootstrapBean, String deploymentUnitName) throws NamingException;

   protected static void addNonSerializableFactory(Hashtable<String, String> environment)
   {
      String nonSerializableFactory = NonSerializableFactory.class.getName();
      String objFactory = environment.get(Context.OBJECT_FACTORIES);
      if (objFactory != null)
      {
         objFactory = nonSerializableFactory + ":" + objFactory;
      }
      else
      {
         objFactory = nonSerializableFactory;
      }

      environment.put(Context.OBJECT_FACTORIES, objFactory);
   }
}