/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2008-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: LifeCycleCallback.java 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */
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.MalformedURLException;
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.JaxWsImplementorInfo;
import org.ow2.jonas.ws.axis2.easybeans.Axis2EJBWebserviceEndpoint;
import org.ow2.jonas.ws.axis2.jaxws.WebservicesContainer;
import org.ow2.jonas.ws.jaxws.IWebServiceEndpoint;
import org.ow2.jonas.ws.jaxws.IWebservicesModule;
import org.ow2.jonas.ws.jaxws.PortMetaData;
import org.ow2.jonas.ws.jaxws.WSException;
import org.ow2.jonas.ws.jaxws.base.JAXWSWebservicesModule;
import org.ow2.jonas.ws.jaxws.ejb.IWebDeployer;
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);



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

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

    /**
     * The Web Deployer used to configure Web contexts for the endpoints.
     */
    private IWebDeployer webDeployer;
    /**
     * Construct a new Callback.
     */
    public LifeCycleCallback() {
        modules = new HashMap<String, IWebservicesModule<WebservicesContainer<Axis2EJBWebserviceEndpoint>>>();
    }



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

        // Archive identifier
        URL moduleURL;
        try {
            moduleURL = new URL("file:/" + info.getArchive().getName());
        } catch (MalformedURLException e2) {
            // TODO Auto-generated catch block
            throw new RuntimeException("the file " + info.getArchive().getName() + " does not exist!",e2);
        }
        String moduleName = info.getArchive().getName();

        IWebservicesModule<WebservicesContainer<Axis2EJBWebserviceEndpoint>> 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 = createWebservicesModule(moduleName);
                        modules.put(moduleName, module);
                    }


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

                    String wsdlLocation = jaxWsImplementorInfo.getWsdlLocation();

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

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

                    // find the URL pattern to use
                    String pattern = getUrlPattern(klass, webServiceInfo, jaxWsImplementorInfo);

                    // 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());
                    Axis2EJBWebserviceEndpoint endpoint;
                    try {
                        //Axis2WSEndpoint endpoint = new Axis2WSEndpoint(klass, IWebServiceEndpoint.EndpointType.EJB, pmd, factory);
                        // Wraps the Endpoint into our own IWSEndpoint implementation
                        endpoint = new Axis2EJBWebserviceEndpoint(
                                klass,
                                pmd,
                                factory,
                                info.getContainer(),
                                beanInfo,
                                moduleURL);

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

            try {

                // Deploy the web context of the endpoints
                webDeployer.deploy(module);
                // WSDL publication
                for (WebservicesContainer<Axis2EJBWebserviceEndpoint> container : module.getContainers()) {

                    // Attempt to publish the service's WSDLs
                    // publishWSDL(container);

                    // Display the endpoint's URLs
                    for (Axis2EJBWebserviceEndpoint endpoint : container.getEndpoints()) {
                        endpoint.displayInfos();
                    }
                }

            } catch (WSException e) {
                // Display a warning
                logger.warn("Webservices endpoints of the EjbJar ''{0}'' cannot be deployed because of some error: {1}",
                            info.getContainer().getName(),
                            e.getMessage(),
                            e);

                // An exception occured, cleanup
                webDeployer.undeploy(module);
                stopWebservicesModule(module);
                modules.remove(moduleName);
            }


        }

    }

    /**
     * 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) {
        // Remove everything before the last '/'
        String context = filename.substring(filename.lastIndexOf(File.separator) + 1);
        int underscoreIndex = context.indexOf('_');
        if (underscoreIndex == -1) {
            // Cut before the last '.'
            context = context.substring(0, context.lastIndexOf('.'));
        } else {
            // Cut before the first '_' for unpacked archives with timestamp
            context = context.substring(0, underscoreIndex);
        }
        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, IWebservicesModule<WebservicesContainer<Axis2EJBWebserviceEndpoint>>> entry : modules.entrySet()) {
            IWebservicesModule<WebservicesContainer<Axis2EJBWebserviceEndpoint>> 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 IWebservicesModule<WebservicesContainer<Axis2EJBWebserviceEndpoint>> module) {


        // Need to unregister the endpoints
        webDeployer.undeploy(module);

        // It will recursively stop containers and endpoints
        module.stop();
    }


    /**
     * Get a valid URL pattern from available deployment info.
     * TODO Should be moved inside the IWebDeployer (another strategy ?)
     * @param klass endpoint class
     * @param webServiceInfo easybeans.xml infos
     * @param jaxWsImplementorInfo merged deployment info
     * @return a valid url pattern
     */
    private String getUrlPattern(final Class<?> klass,
                                 final IWebServiceInfo webServiceInfo,
                                 final JaxWsImplementorInfo jaxWsImplementorInfo) {

        String pattern;

        // If user has specified an endpoint address, use it
        if ((webServiceInfo != null) && (webServiceInfo.getEndpointAddress() != null)) {

            // User defined address
            pattern = webServiceInfo.getEndpointAddress();
            if (!pattern.startsWith("/")) {
                // Pattern needs to start with a '/'
                pattern = "/" + pattern;
            }
        } else {

            // Default naming strategy
            String serviceName = jaxWsImplementorInfo.getServiceName().getLocalPart();
            if (!"".equals(serviceName)) {
                // default pattern : /{service-name}
                pattern = "/" + serviceName;
            } else {
                // else /{class-name}Service
                pattern = "/" + klass.getSimpleName() + "Service";
            }
        }
        return pattern;
    }

    /**
     * Set the web deployer to be used to manage web contexts.
     * @param webDeployer deployer
     */
    public void setWebDeployer(final IWebDeployer webDeployer) {
        this.webDeployer = webDeployer;
    }

    protected JAXWSWebservicesModule<WebservicesContainer<Axis2EJBWebserviceEndpoint>> createWebservicesModule(final String name) {
        return new JAXWSWebservicesModule<WebservicesContainer<Axis2EJBWebserviceEndpoint>>(name);
    }
    protected WebservicesContainer<Axis2EJBWebserviceEndpoint> createWebservicesContainer(final String name) {
        return new WebservicesContainer<Axis2EJBWebserviceEndpoint>(name);
    }
}
