/**
 * 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.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.HandlerChain;
import javax.jws.WebService;

import org.ow2.easybeans.api.EZBContainerCallbackInfo;
import org.ow2.easybeans.api.Factory;
import org.ow2.easybeans.api.bean.info.IBeanInfo;
import org.ow2.easybeans.api.bean.info.IWebServiceInfo;
import org.ow2.easybeans.container.EmptyLifeCycleCallBack;
import org.ow2.easybeans.container.session.stateless.StatelessSessionFactory;
import org.ow2.jonas.ws.axis2.JOnASJaxWsImplementorInfo;
import org.ow2.jonas.ws.axis2.jaxws.Axis2WSEndpoint;
import org.ow2.jonas.ws.axis2.jaxws.WebservicesContainer;
import org.ow2.jonas.ws.axis2.jaxws.WebservicesModule;
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.jonas.ws.jaxws.base.JAXWSWebservicesContainer;
import org.ow2.jonas.ws.jaxws.util.JAXWSClassUtils;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * Callback for Axis2.
 * @author youchao
 * @author Guillaume Sauthier
 * @author Florent Benoit
 * @author xiaoda
 */
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>();

    /**
     * A Module that contains WSContainer and Endpoints.
     */
    private Map<String, WebservicesModule> modules;

    /**
     * Construct a new Callback.
     */
    public LifeCycleCallback() {
        modules = new HashMap<String, WebservicesModule>();
    }


    /**
     * @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) {

        // Archive identifier
        String moduleName = info.getArchive().getName();

        WebservicesModule module = null;

        // 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);

                // An EJB exposed as a JAX-WS web services HAS TO be annotated
                // with @WebService or @WebServiceProvider
                if (JAXWSClassUtils.isWebService(klass)) {

                    // Extract merged webservices deploy time informations
                    IBeanInfo beanInfo = factory.getBeanInfo();
                    IWebServiceInfo webServiceInfo = beanInfo.getWebServiceInfo();


                    JOnASJaxWsImplementorInfo jaxWsImplementorInfo;
                    if (webServiceInfo != null) {
                        jaxWsImplementorInfo = new JOnASJaxWsImplementorInfo(klass, webServiceInfo);
                    } else {
                        jaxWsImplementorInfo = new JOnASJaxWsImplementorInfo(klass);
                    }


                    // Get the WSModule for this archive if not already set
                    module = modules.get(moduleName);
                    if (module == null) {
                        module = new WebservicesModule(moduleName);
                        modules.put(moduleName, module);
                    }


                    // Get a Container for all services deployed using the same WSDL
                    WebservicesContainer container = (WebservicesContainer)module.findContainer(jaxWsImplementorInfo.getWsdlLocation());
                    if (container == null) {
                        // Create a new Container
                        container = new WebservicesContainer(jaxWsImplementorInfo.getWsdlLocation());
                        module.addContainer(container);
                    }

                    String wsdlLocation = jaxWsImplementorInfo.getWsdlLocation();

                    if (wsdlLocation == null || wsdlLocation.equals("")) {
                        logger.warn("The wsdl location is not specified!");
                    }


                    // 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());

                    StringBuffer handlerXML = new StringBuffer();
                    try {
                        HandlerChain hc = klass.getAnnotation(HandlerChain.class);

                        if (hc != null) {
                            URL handlerURL = klass.getClassLoader().getResource(hc.file());
                            BufferedReader br = new BufferedReader(new InputStreamReader(handlerURL.openStream()));

                            String temp = null;
                            temp = br.readLine();
                            while (temp != null) {
                                handlerXML.append(temp);
                                temp = br.readLine();
                            }
                            pmd.setHandlerXML(handlerXML.toString());
                        }

                    } catch (IOException e) {
                        throw new RuntimeException("Unable to Get the handler description file for " + serviceName + "!", e);
                    } finally {
                        if(pmd.getHandlerXML() != null) {
                            logger.debug("Found handlers in this package!");
                        }
                    }



                    pmd.setContextRoot(contextRoot);
                    pmd.setUrlPattern(pattern);
                    if (wsdlLocation != null && !wsdlLocation.equals("")) {
                        pmd.setWSDLLocation(wsdlLocation);
                    }

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

                    ClassLoader old = Thread.currentThread().getContextClassLoader();

                    Thread.currentThread().setContextClassLoader(klass.getClassLoader());

                    Axis2WSEndpoint endpoint = new Axis2WSEndpoint(klass, IWebServiceEndpoint.EndpointType.EJB, pmd, factory);

                    try {
                        // init axis2
                        endpoint.init();
                    } catch (Exception e1) {
                        //e1.printStackTrace();
                        throw new RuntimeException("Exception occurs when creating endpoint for" + serviceName + "!",e1);
                    } finally {
                        // reset
                        Thread.currentThread().setContextClassLoader(old);
                    }
                    container.addEndpoint(endpoint);

                }
            }
        }

        if(module != null) {
            module.start();

            for (JAXWSWebservicesContainer container : module.getContainers()) {

                // Register the endpoints
                for (IWebServiceEndpoint endpoint : container.getEndpoints()) {
                    // 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 {

                        // Register our endpoint in the webcontainer
                        manager.registerWSEndpoint(endpoint);

                        // Print infos
                        endpoint.displayInfos();
                    } catch (WSException e) {
                        // Log an error
                        logger.error("Unable to register endpoint ''{0}''", endpoint, e);

                        // Try to unregister previous stuff
                        try {
                            manager.unregisterWSEndpoint(endpoint);
                        } catch (WSException e1) {
                            logger.error("Unable to unregister endpoint ''{0}'' after a failed deployment", endpoint, e);
                        }
                    }
                }
            }
        }

    }

    /**
     * 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() {
        logger.debug("Stop ''{0}''", this);

        // Stop all the modules
        for (Map.Entry<String, WebservicesModule> entry : modules.entrySet()) {
            WebservicesModule module = entry.getValue();
            // Stop the module
            stopWebservicesModule(module);
        }
        // Clear the map
        modules.clear();
    }

    /**
     * Stop the given module.
     * @param module module to be stopped
     */
    private void stopWebservicesModule(final WebservicesModule module) {

        // Need to unregister the endpoints
        for (JAXWSWebservicesContainer container : module.getContainers()) {
            for (IWebServiceEndpoint endpoint : container.getEndpoints()) {
                try {
                    manager.unregisterWSEndpoint(endpoint);
                } catch (WSException wse) {
                    // Do not rethrow the Exception directly: try to
                    // undeploy the other endpoints before
                    logger.warn("Cannot unregister endpoint ''{0}'', continue processing", endpoint, wse);
                }
            }
        }
        // It will recursively stop containers and endpoints
        module.stop();
    }


}
