package org.jboss.as.naming.javaee;

import org.jboss.deployers.structure.spi.DeploymentUnit;
import org.jboss.metadata.ear.jboss.JBossAppMetaData;
import org.jboss.reloaded.naming.deployers.javaee.JavaEEApplicationInformer;
import org.jboss.system.metadata.ServiceDeployment;

/**
 * @author <a href="cdewolf@redhat.com">Carlo de Wolf</a>
 */
public class NamingJavaEEApplicationInformer implements JavaEEApplicationInformer
{
   private static final String REQUIRED_ATTACHMENTS[] = { JBossAppMetaData.class.getName(), ServiceDeployment.class.getName() };

   public String getApplicationName(DeploymentUnit deploymentUnit) throws IllegalArgumentException
   {
      if(!isJavaEEApplication(deploymentUnit))
         return null;

      String name = deploymentUnit.getSimpleName();
      return name.substring(0, name.length() - 4);
   }

   public boolean isJavaEEApplication(DeploymentUnit deploymentUnit)
   {
      return deploymentUnit.isAttachmentPresent(JBossAppMetaData.class) || isTopLevelServiceArchive(deploymentUnit);
   }

   /**
    * In a deployment consisting of x.sar/ejbs.jar, the x.sar substitutes an EAR.
    */
   protected boolean isTopLevelServiceArchive(DeploymentUnit deploymentUnit)
   {
      return deploymentUnit.isTopLevel() && deploymentUnit.isAttachmentPresent(ServiceDeployment.class);
   }

   public String[] getRequiredAttachments()
   {
      return REQUIRED_ATTACHMENTS;
   }   
}
