/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2008 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$ 
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.ws.axis2.easybeans.ext;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;
import org.ow2.easybeans.api.EZBContainerCallbackInfo;
import org.ow2.easybeans.api.Factory;
import org.ow2.easybeans.container.EmptyLifeCycleCallBack;
import org.ow2.easybeans.container.session.stateless.StatelessSessionFactory;
import org.ow2.jonas.ws.axis2.jaxws.Axis2WSEndpoint;
import org.ow2.jonas.ws.jaxws.IWebServiceDeploymentManager;
import org.ow2.jonas.ws.jaxws.IWebServiceEndpoint;
import org.ow2.jonas.ws.jaxws.PortMetaData;
import org.ow2.jonas.ws.jaxws.WSException;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * Callback for Axis2.
 * @author youchao
 * @author Guillaume Sauthier
 * @author Florent Benoit
 */
public class LifeCycleCallback extends EmptyLifeCycleCallBack {

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

    /**
     * The WS deployment manager.
     */
    private IWebServiceDeploymentManager manager;

    /**
     * List of deployed endpoints.
     */
    private List<IWebServiceEndpoint> endpoints = new ArrayList<IWebServiceEndpoint>();

    /**
     * @param manager the manager to set
     */
    public void setManager(final IWebServiceDeploymentManager manager) {
        this.manager = manager;
    }

    /**
     * Called when container is starting.
     * @param info some information on the container which is starting.
     */
    @Override
    public void start(final EZBContainerCallbackInfo info) {

        // Iterates over the factories
        Map<String, Factory<?, ?>> factories = info.getFactories();
        for (Factory<?, ?> f : factories.values()) {

            // Only for @Stateless
            if (f instanceof StatelessSessionFactory) {

                StatelessSessionFactory factory = (StatelessSessionFactory) f;
                Class<?> klass = factory.getBeanClass();

                // An EJB exposed as a JAX-WS web services HAS TO be annotated
                // with @WebService
                WebService ws = klass.getAnnotation(WebService.class);

                // only for @WebService
                if (ws != null) {

                    String wsdlName = ws.wsdlLocation();
                    // Load the WSDL if possible
                    URL url = null;
                    if (wsdlName != null) {
                        url = klass.getClassLoader().getResource(wsdlName);
                        if (url == null) {
                            try {
                                url = new URL(wsdlName);
                            } catch (MalformedURLException ex2) {
                                url = klass.getClassLoader().getResource("/" + wsdlName);
                            }
                        }
                    }

                    // TODO: fix out the url pattern, i.e if the name is null
                    // find the URL pattern to use
                    String pattern = null;

                    // But values could be overrided
                    // TODO: use the merged metadata here !
                    String serviceName = ws.serviceName();
                    String portName = ws.portName();
                    String name = ws.name();

                    if (!"".equals(portName)) {
                        // default pattern : service-name/port-name
                        pattern = "/" + serviceName + "/" + portName;
                    } else {
                        pattern = "/" + serviceName + "/" + name;
                    }

                    // Creates PortMetaData to hold deployment/runtime
                    // information
                    // about the web service
                    PortMetaData pmd = new PortMetaData();
                    String contextRoot = extractContextRoot(info.getArchive().getName());
                    pmd.setContextRoot(contextRoot);
                    pmd.setUrlPattern(pattern);

                    logger.info("PortMetaData [context:{0}, pattern:{1}]", pmd.getContextRoot(), pmd.getUrlPattern());

                    Axis2WSEndpoint endpoint = new Axis2WSEndpoint(klass, IWebServiceEndpoint.EndpointType.EJB, pmd, factory);
                    try {
                        // init axis2
                        endpoint.init();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    // OK, We have a endpoint, in some way, we have to register
                    // it to the web container
                    // So here we should have an IWSDeploymentManager instance
                    // that we can use

                    try {
                        manager.registerWSEndpoint(endpoint);
                    } catch (WSException e) {
                        // Log an error
                        logger.error("Unable to register endpoint {0}", endpoint, e);
                        throw new RuntimeException("Endpoint not deployed completely", e);
                    }

                    endpoint.start();

                    // Add the endpoint in the list
                    endpoints.add(endpoint);

                    logger.info("Endpoint {0} inited", klass.getName());

                }
            }
        }
        logger.info("Axis2 ready for " + info.getArchive());
    }

    /**
     * Extract a context-root name from the archive filename.
     * @param filename archive filename
     * @return a context-root which is the last part of the filename minus the
     *         extension
     */
    private static String extractContextRoot(final String filename) {
        // TODO: the filename coming out is ugly:-(
        String context = filename.substring(filename.lastIndexOf(File.separator) + 1);
        context = context.substring(0, context.lastIndexOf('.'));
        return context;
    }

    /**
     * Called when container is stopping.
     * @param info some information on the container which is stopping.
     */
    @Override
    public void stop(final EZBContainerCallbackInfo info) {

        stop();
        logger.info("axis2 stopped for " + info.getArchive());

    }

    /**
     * This stop method is not directly called by the EJB container. The
     * lifecycle object itself has decided to stop (maybe one of its
     * dependencies is now unavailable)
     */
    public void stop() {

        List<WSException> exceptions = new ArrayList<WSException>();

        for (IWebServiceEndpoint endpoint : endpoints) {
            try {
                // Stop and unregister
                endpoint.stop();
                manager.unregisterWSEndpoint(endpoint);
            } catch (WSException e) {
                // Do not rethrow the Exception directly: try to
                // undeploy the other endpoints before
                exceptions.add(e);
            }
        }

        // Clear the list
        endpoints.clear();

        // Warn the user for each of the unregistration that have failed
        // TODO add more details (names, ...)
        for (WSException exception : exceptions) {
            logger.warn("Unable to stop/unregister endpoint", exception);
        }
    }

}
