/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library 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 library 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 library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.cdi.weld.internal.deployment;

import java.net.URL;
import java.util.Iterator;

import org.jboss.weld.bootstrap.spi.Deployment;
import org.ow2.jonas.cdi.weld.IDeploymentBuilder;
import org.ow2.jonas.cdi.weld.IWeldService;
import org.ow2.util.archive.api.ArchiveException;
import org.ow2.util.archive.api.IArchive;
import org.ow2.util.archive.api.IArchiveManager;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * A {@code DefaultDeploymentBuilder} is in charge of the {@code Deployment} instance
 * construction from a given {@code IArchive}.
 *
 * @author Guillaume Sauthier
 */
public class DefaultDeploymentBuilder implements IDeploymentBuilder {

    /**
     * Logger.
     */
    private static Log logger = LogFactory.getLog(DefaultDeploymentBuilder.class);

    /**
     * Location (in web application) of the beans.xml marker file.
     */
    public final static String WEBINF_BEANS_XML = "WEB-INF/beans.xml";

    /**
     * Location (in jars) of the beans.xml marker file.
     */
    public final static String METAINF_BEANS_XML = "META-INF/beans.xml";

    /**
     * Used to create sub-archives.
     */
    private IArchiveManager manager;

    /**
     * Weld service.
     */
    private IWeldService weld;

    /**
     * Bind the archive manager.
     */
    public void setArchiveManager(IArchiveManager manager) {
        this.manager = manager;
    }

    /***
     * Bind the Weld utility service
     */
    public void setWeldService(IWeldService weld) {
        this.weld = weld;
    }

    /**
     * Build a Web related {@code Deployment} archive.
     *
     * @param archive a web archive
     * @return a Weld configured {@code Deployment} instance.
     */
    public Deployment buildWebDeployment(IArchive archive) {

        logger.debug("Building Weld Deployment for {0}", archive);

        // Create an empty Deployment
        DefaultDeployment deployment = new DefaultDeployment();

        // The default BDA for the webapp
        // Corresponds to WEB-INF/classes content
        DefaultBeanDeploymentArchive bda = new DefaultBeanDeploymentArchive(archive.getName(),
                                                                            archive,
                                                                            deployment.getServices());

        // Get the beans.xml
        try {
            URL beansXml = archive.getResource(WEBINF_BEANS_XML);
            bda.getBeansXml().add(beansXml);
        } catch (ArchiveException e) {
            throw new IllegalStateException("Requires a " + WEBINF_BEANS_XML + " entry.", e);
        }

        // add the BDA in the Deployment
        deployment.getBeanDeploymentArchives().add(bda);

        // Explore WEB-INF/lib/*.jar
        try {
            for (Iterator<String> i = archive.getEntries(); i.hasNext(); ) {

                String name = i.next();

                if (name.startsWith("WEB-INF/lib/") && name.endsWith(".jar")) {

                    // TODO only checks archive directly under WEB-INF/lib/
                    URL webInfLibraryUrl = archive.getResource(name);

                    logger.debug("Traversing library {0}", webInfLibraryUrl);

                    IArchive archiveLibrary = manager.getArchive(webInfLibraryUrl);
                    try {
                        // Get the beans.xml
                        URL beansXml = archive.getResource(METAINF_BEANS_XML);
                        bda.getBeansXml().add(beansXml);
                        DefaultBeanDeploymentArchive libraryBda = new DefaultBeanDeploymentArchive(archiveLibrary.getName(),
                                                                                                   archiveLibrary,
                                                                                                   deployment.getServices());

                        deployment.getBeanDeploymentArchives().add(libraryBda);
                    } catch (ArchiveException e) {
                        // No beans.xml here
                        // Do not include this archive as BDA
                    }
                }
            }
        } catch (ArchiveException e) {
            throw new IllegalStateException("Cannot explore archive " + archive, e);
        }

        // Connect the Collection of BDA together (all beans are accessible to all archives)
        weld.connectBeanDeploymentArchives(deployment.getBeanDeploymentArchives(),
                                           deployment.getBeanDeploymentArchives());

        return deployment;
    }
}
