/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-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.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.wsdl.Definition;
import javax.wsdl.Port;
import javax.wsdl.Service;
import javax.xml.namespace.QName;

import org.ow2.jonas.deployment.common.HandlerDesc;
import org.ow2.jonas.deployment.ws.MappingFile;
import org.ow2.jonas.deployment.ws.PortComponentDesc;
import org.ow2.jonas.deployment.ws.SSBPortComponentDesc;
import org.ow2.jonas.deployment.ws.ServiceDesc;
import org.ow2.jonas.deployment.ws.ServiceRefDesc;

import org.apache.velocity.VelocityContext;



/**
 * This class allows to create the Velocity Context used to build the generated
 * sources with the Velocity templates.
 *
 * @author Xavier Delplanque (Bull)
 */
public class VContextFactory {

    /**
     * Provider property name
     */
    public static final String PROVIDER = "provider";

    /**
     * JOnAS EJB Provider name
     */
    public static final String EJB_PROVIDER = "JOnASEJB";

    /**
     * Default RPC Provider name
     */
    public static final String RPC_PROVIDER = "RPC";

    /**
     * Mapping property name
     */
    public static final String MAPPINGS = "mappings";

    /**
     * Port Components list property name
     */
    public static final String PORT_COMPONENTS = "portComponents";

    /**
     * WSDL directory in Webapp
     */
    private static final String WEB_WSDL = "WEB-INF/wsdl/";

    /**
     * WSDL directory in EjbJar/Client
     */
    private static final String META_WSDL = "META-INF/wsdl/";

    /**
     * Empty Constructor for Utility class
     */
    private VContextFactory() {
    }

    /**
     * Creates the Velocity Context used to build the generated files with the
     * Velocity templates.
     *
     * @param sd The ServiceDesc Deployment Descriptor
     *
     * @return a VelocityContext customized with the SD
     */
    public static VelocityContext getContext(ServiceDesc sd) {

        VelocityContext vc = new VelocityContext();

        // Set provider value
        String wsdl;
        if (sd.getPortComponents().get(0) instanceof SSBPortComponentDesc) {
            // EJB Provider
            vc.put(PROVIDER, EJB_PROVIDER);
            // get wsdl name
            wsdl = sd.getWSDL().getName().substring(META_WSDL.length());
        } else {
            // JAXRPC Provider
            vc.put(PROVIDER, RPC_PROVIDER);
            // get wsdl name
            wsdl = sd.getWSDL().getName().substring(WEB_WSDL.length());
        }

        // Add all ports
        List ports = sd.getPortComponents();
        List portComponents = new Vector();
        for (Iterator it = ports.iterator(); it.hasNext();) {
            PortComponentDesc pcd = (PortComponentDesc) it.next();
            portComponents.add(new VcPortComponent(pcd, wsdl));
        }
        vc.put(PORT_COMPONENTS, portComponents);

        // add types mappings
        List mappings = new Vector();
        MappingFile mf = sd.getMapping();
        for (Iterator m = mf.getXmlTypeMappings(); m.hasNext();) {
            QName xml = (QName) m.next();
            String classname = mf.getClassname(xml);

            // if we have an Array, Axis use a different representation
            if (classname.endsWith("[]")) {
                mappings.add(new VcArrayMapping(xml, classname));
            } else {
                mappings.add(new VcBeanMapping(xml, classname));
            }
        }
        vc.put(MAPPINGS, mappings);

        return vc;
    }

    /**
     * Creates the Velocity Context used to build the generated files with the
     * Velocity templates.
     *
     * @param sr The ServiceRefDesc Deployment Descriptor
     *
     * @return a VelocityContext customized with the SR
     */
    public static VelocityContext getContext(ServiceRefDesc sr) {

        VelocityContext vc = new VelocityContext();

        Hashtable pcds = new Hashtable();

        // for each service-ref handler
        List hrs = sr.getHandlerRefs();

        Vector commonh = new Vector();
        for (Iterator itHr = hrs.iterator(); itHr.hasNext();) {
            HandlerDesc hr = (HandlerDesc) itHr.next();
            List pcns = hr.getPortNames();

            if (pcns.size() != 0) {
                // a port name list is defined : add the handler to each
                // specified port
                for (Iterator itPcn = pcns.iterator(); itPcn.hasNext();) {
                    String pcn = (String) itPcn.next();
                    if (!pcds.containsKey(pcn)) {
                        pcds.put(pcn, new Vector());
                    }
                    ((Vector) pcds.get(pcn)).add(hr);
                }
            } else {
                // no port name is specified : the handler is added to each
                // port
                commonh.add(hr);
            }
        }

        // now, we can create the port component list
        Vector portComponents = new Vector();

        // if there is not port-component-ref
        if (pcds.isEmpty()) {
            Definition def = sr.getWSDLFile().getDefinition();
            Service s = def.getService(sr.getServiceQName());
            Map ports = s.getPorts();
            // for each wsdl:port
            for (Iterator i = ports.values().iterator(); i.hasNext();) {
                Port p = (Port) i.next();
                portComponents.add(new VcPortComponent(p.getName(), commonh));
            }
        } else {
            for (Enumeration enPc = pcds.keys(); enPc.hasMoreElements();) {
                String pcn = (String) enPc.nextElement();
                // add common handlers to the list
                Vector pchrs = (Vector) pcds.get(pcn);
                pchrs.addAll(commonh);
                portComponents.add(new VcPortComponent(pcn, pchrs));
            }
        }

        vc.put(PORT_COMPONENTS, portComponents);

        // add types mappings
        List mappings = new Vector();
        MappingFile mf = sr.getMappingFile();
        if (mf != null) {
            for (Iterator m = mf.getXmlTypeMappings(); m.hasNext();) {
                QName xml = (QName) m.next();
                String classname = mf.getClassname(xml);

                // if we have an Array, Axis use a different representaion
                if (classname.endsWith("[]")) {
                    mappings.add(new VcArrayMapping(xml, classname));
                } else {
                    mappings.add(new VcBeanMapping(xml, classname));
                }
            }
        }
        vc.put(MAPPINGS, mappings);

        return vc;
    }
}