/**
 * JOnAS : Java(TM) OpenSource Application Server
 * Copyright (C) 2004 Bull S.A.
 * 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.generators.wsgen.generator.axis;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.ow2.jonas.deployment.ws.JaxRpcPortComponentDesc;
import org.ow2.jonas.deployment.ws.PortComponentDesc;
import org.ow2.jonas.deployment.ws.ServiceDesc;
import org.ow2.jonas.generators.genbase.GenBaseException;
import org.ow2.jonas.generators.genbase.archive.Archive;
import org.ow2.jonas.generators.genbase.archive.WebApp;
import org.ow2.jonas.generators.genbase.generator.Config;
import org.ow2.jonas.generators.wsgen.WsGenException;
import org.ow2.jonas.generators.wsgen.ddmodifier.WebServicesDDModifier;
import org.ow2.jonas.generators.wsgen.ddmodifier.WsEndpointDDModifier;
import org.ow2.jonas.generators.wsgen.generator.WsEndpointGenerator;
import org.ow2.jonas.lib.util.Log;

import org.apache.velocity.VelocityContext;




import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * Generate Axis specific config files for Endpoint
 *
 * @author Guillaume Sauthier
 */
public class AxisWsEndpointGenerator extends WsEndpointGenerator {

    /**
     * unique JVelocity instance
     */
    private static JVelocity jvelocity = null;

    /**
     * logger
     */
    private static Logger logger = Log.getLogger(Log.JONAS_WSGEN_PREFIX);

    /**
     * Axis Servlet classname
     */
    private static final String AXIS_SERVLET_CLASS = "org.ow2.jonas.ws.axis.JAxisServlet";

    /**
     * init-param name for declaring server configuration file
     */
    private static final String SERVER_CONFIG = "axis.serverConfigFile";

    /**
     * WSDD Extension suffix
     */
    private static final String WSDD_SUFFIX = ".wsdd";

    /**
     * WSDD Extension prefix
     */
    private static final String WSDD_PREFIX = "deploy-server-";

    /**
     * count generated files
     */
    private static int count = 0;

    /**
     * generated server-config file
     */
    private File generatedServerConfig;

    /**
     * Creates a new AxisWsEndpointGenerator
     *
     * @param config Generator Configuration
     * @param serviceDesc WebService Endpoint description
     * @param ddm Web DD Modifier
     * @param wsddm webservices.xml DD modifier
     *
     * @throws GenBaseException When instanciation fails
     * @throws WsGenException When instanciation fails.
     */
    public AxisWsEndpointGenerator(Config config, ServiceDesc serviceDesc, WsEndpointDDModifier ddm,
            WebServicesDDModifier wsddm, Archive arch) throws GenBaseException, WsGenException {
        super(config, serviceDesc, ddm, wsddm, arch);

        // init velocity
        if (jvelocity == null) {
            String packageName = this.getClass().getPackage().getName();
            packageName = packageName.replace('.', '/');
            jvelocity = new JVelocity(packageName + "/deploy_endpoint.vm");
        }
    }

    /**
     * Generate server side configuration file
     *
     * @throws WsGenException When generation fails
     */
    public void generate() throws WsGenException {
        String sName = getService().getName();

        // construct VelocityContext
        VelocityContext vc = VContextFactory.getContext(getService());

        // Generate file
        String filename = WSDD_PREFIX + (count++) + WSDD_SUFFIX;
        generatedServerConfig = new File(getSources(), filename);
        jvelocity.generate(generatedServerConfig, vc);

        // remove existing servlets
        for (Iterator i = getService().getPortComponents().iterator(); i.hasNext();) {
            Object obj = i.next();
            if (obj instanceof JaxRpcPortComponentDesc) {
                JaxRpcPortComponentDesc jax = (JaxRpcPortComponentDesc) obj;

                if (logger.isLoggable(BasicLevel.DEBUG)) {
                    logger.log(BasicLevel.DEBUG, "Removing servlet '" + jax.getSibLink() + "'");
                }

                // remove servlet mapping
                getModifier().removeServletMapping(jax.getSibLink());
                // remove old servlet
                getModifier().removeServlet(jax.getSibLink());
                // change sib-link
                getWsModifier().changeServletLink(sName, jax.getSibLink(), sName);
            }
        }

        // and use our own
        getModifier().addServlet(sName, AXIS_SERVLET_CLASS);
        getModifier().addServletParam(sName, SERVER_CONFIG, filename);

        // setup servlet-mappings
        boolean requireDefaultMapping = false;
        List usedServletMappings = new Vector();
        for (Iterator i = getService().getPortComponents().iterator(); i.hasNext();) {
            PortComponentDesc pcd = (PortComponentDesc) i.next();
            String mapping = pcd.getMapping();
            if (mapping != null) {
                // port has specified an endpoint URI
                // use it for servlet-mapping
                if (!usedServletMappings.contains(mapping)) {
                    usedServletMappings.add(mapping);

                    if (logger.isLoggable(BasicLevel.DEBUG)) {
                        logger.log(BasicLevel.DEBUG, "Adding servlet-mapping for '" + sName + "' -> '" + mapping + "'");
                    }

                    getModifier().addServletMapping(sName, mapping);
                }
            } else {
                // no specified endpoint uri for the port
                requireDefaultMapping = true;
            }
        }
        if (requireDefaultMapping) {
            // try to set a default mapping
            String defaultEndpointURI = getService().getEndpointURI();
            if (defaultEndpointURI == null) {
                // default behavior
                getModifier().addServletMapping(sName, "/" + sName + "/*");
            } else {
                // use retieved value
                getModifier().addServletMapping(sName, defaultEndpointURI);
            }
        }

    }

    /**
     * Add generated files in given Archive
     *
     * @param archive WebApp archive
     *
     * @throws WsGenException When cannot add files in archive
     */
    public void addFiles(Archive archive) throws WsGenException {
        // archive must be a WebApp
        if (!(archive instanceof WebApp)) {
            String err = getI18n().getMessage("AxisWsEndpointGenerator.addFiles.illegal", archive.getRootFile());
            throw new IllegalArgumentException(err);
        }

        WebApp web = (WebApp) archive;
        web.addFileIn("WEB-INF/", generatedServerConfig);

    }
}