/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2009 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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: WebservicesContainer.java 16955 2009-03-23 15:17:41Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.ws.cxf.jaxws;

import static org.ow2.jonas.lib.util.Log.setComponentLogLevel;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.wsdl.WSDLException;

import org.apache.cxf.Bus;
import org.apache.cxf.service.model.ServiceInfo;
import org.apache.cxf.wsdl.WSDLManager;
import org.apache.cxf.wsdl11.ServiceWSDLBuilder;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Level;
import org.ow2.jonas.ws.cxf.BusCreator;
import org.ow2.jonas.ws.cxf.http.JOnASDestination;
import org.ow2.jonas.ws.cxf.util.WSDLUtils;
import org.ow2.jonas.ws.jaxws.IWebServiceEndpoint;
import org.ow2.jonas.ws.jaxws.base.JAXWSWebservicesContainer;
import org.ow2.jonas.ws.publish.PublicationInfo;
import org.ow2.jonas.ws.publish.PublishableDefinition;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * The WebservicesContainer represents a group of endpoints sharing the same WSDL Definition.
 * Grouping is based on the WSDL location value. <br/>
 * For example, if 2 endpoints (from the same archive) are declaring the same WSDL location
 * ('META-INF/wsdl/definition.wsdl' for example), they will be grouped in the same container.
 *
 * @author Guillaume Sauthier
 */
public class WebservicesContainer<T extends IWebServiceEndpoint> extends JAXWSWebservicesContainer<T> {

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

    /**
     * Endpoints of the group share the same Bus instance.
     */
    private Bus bus;

    /**
     * Construct the group.
     * @param name Shared WSDL Location
     */
    public WebservicesContainer(final String name) {
        super(name);

        // Init the Bus
        BusCreator creator = new BusCreator();
        bus = creator.initBus();

    }

    /**
     * @return the shared Bus instance.
     */
    public Bus getBus() {
        return this.bus;
    }

    /**
     * Stops the container.
     * Recursively stops inner endpoints.
     */
    @Override
    public void stop() {

        // Stop the endpoints first
        super.stop();

        // Stop the Bus of the container
        // Bus start/stop operations are extra verbose
        Level old = setComponentLogLevel("org.apache.cxf", BasicLevel.LEVEL_ERROR);
        Level old2 = setComponentLogLevel("org.springframework", BasicLevel.LEVEL_ERROR);

        this.bus.shutdown(true);

        // Reset log levels
        setComponentLogLevel("org.apache.cxf", old);
        setComponentLogLevel("org.springframework", old2);

    }

    /**
     * @return list of publishable definition that will be used by the publisher
     */
    public List<PublishableDefinition> getPublishableDefinitions() {
        // Get WSDL location
        String wsdlLocation = getName();

        // Only 1 definition if there is a WSDL location, else 1 definition by endpoint
        List<PublishableDefinition> publishableDefinitionList = new ArrayList<PublishableDefinition>();

        // Two cases : with or without a WSDL
        if (wsdlLocation != null && !"".equals(wsdlLocation)) {
            // 1st case : With a WSDL location
            PublishableDefinition publishableDefinition = new PublishableDefinition();
            publishableDefinitionList.add(publishableDefinition);

            // There is a WSDL, only one definition and publication info
            PublicationInfo publicationInfo = new PublicationInfo();
            publicationInfo.setOriginalWsdlFilename(wsdlLocation);
            publishableDefinition.setPublicationInfo(publicationInfo);

            // Get the WSDL manager
            WSDLManager wsdlManager = bus.getExtension(WSDLManager.class);
            try {
                publishableDefinition.setDefinition(wsdlManager.getDefinition(wsdlLocation));
            } catch (WSDLException e) {
                logger.error("Unable to load WSDL ''{0}''", wsdlLocation, e);
            }

        } else {
            // No WSDL, needs to publish a WSDL for each endpoint
            Collection<T> endPoints = getEndpoints();
            if (endPoints != null) {
                for (IWebServiceEndpoint endpoint : endPoints) {
                    if (endpoint instanceof CXFWSEndpoint) {
                        CXFWSEndpoint cxfEndPoint = (CXFWSEndpoint) endpoint;

                        PublishableDefinition publishableDefinition = new PublishableDefinition();
                        JOnASDestination destination = cxfEndPoint.getDestination();
                        ServiceInfo serviceInfo = destination.getEndpointInfo().getService();

                        // Publication info
                        PublicationInfo publicationInfo = new PublicationInfo();
                        publishableDefinition.setPublicationInfo(publicationInfo);
                        // Set a name based on the service name
                        publicationInfo.setOriginalWsdlFilename(serviceInfo.getName().getLocalPart() + ".wsdl");



                        // Definition
                        try {
                            ServiceWSDLBuilder builder = new ServiceWSDLBuilder(bus, serviceInfo);
                            publishableDefinition.setDefinition(builder.build());
                        } catch (WSDLException e) {
                            logger.error("Unable to load WSDL ''{0}''", wsdlLocation, e);
                        }
                    }
                }
            }
        }

        // Update publication directory if container contains one
        String directory = getWsdlPublicationDirectory();
        if (directory != null) {
            File dir = new File(directory);
            for (PublishableDefinition publishableDefinition : publishableDefinitionList) {
                publishableDefinition.getPublicationInfo().setPublicationDirectory(dir);

            }
        }

        // Update definition
        for (PublishableDefinition publishableDefinition : publishableDefinitionList) {
            WSDLUtils.updateEndpointAddresses(publishableDefinition.getDefinition(), this);
        }

        return publishableDefinitionList;
    }
}
