/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2003-2004 Bull S.A.
 * Contact: jonas-team@objectweb.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.objectweb.jonas_ws.wsgen.modifier;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.jar.Attributes;

import org.w3c.dom.Document;

import org.objectweb.jonas_lib.genbase.GenBaseException;
import org.objectweb.jonas_lib.genbase.archive.Application;
import org.objectweb.jonas_lib.genbase.archive.Archive;
import org.objectweb.jonas_lib.genbase.archive.DummyApplication;
import org.objectweb.jonas_lib.genbase.archive.DummyWebApp;
import org.objectweb.jonas_lib.genbase.archive.Ejb;
import org.objectweb.jonas_lib.genbase.archive.EjbJar;
import org.objectweb.jonas_lib.genbase.archive.WebApp;
import org.objectweb.jonas_lib.genbase.modifier.ArchiveModifier;
import org.objectweb.jonas_lib.version.Version;

import org.objectweb.jonas_ws.deployment.api.ServiceDesc;
import org.objectweb.jonas_ws.deployment.api.ServiceRefDesc;
import org.objectweb.jonas_ws.wsgen.ddmodifier.ContextDDModifier;
import org.objectweb.jonas_ws.wsgen.ddmodifier.WebJettyDDModifier;
import org.objectweb.jonas_ws.wsgen.ddmodifier.WsClientDDModifier;
import org.objectweb.jonas_ws.wsgen.ddmodifier.WsEndpointDDModifier;
import org.objectweb.jonas_ws.wsgen.generator.Generator;
import org.objectweb.jonas_ws.wsgen.generator.GeneratorFactory;
import org.objectweb.jonas_ws.wsgen.generator.SecurityGenerator;

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

/**
 * Modify a given EjbJar.
 *
 * @author Guillaume Sauthier
 */
public class EjbJarModifier extends ArchiveModifier {

    /** modified ejbjar */
    private EjbJar ejbjar = null;

    /**
     * Creates a new EjbJarModifier object.
     *
     * @param ejbjar EjbJar Archive
     */
    public EjbJarModifier(EjbJar ejbjar) {
        super(ejbjar);
        this.ejbjar = ejbjar;
    }

    /**
     * modify the current EjbJar. If EjbJar is contained in not an application
     * and have webservices endpoints, A DummyApplication is created and
     * modification process launched against the newly created application. If
     * EjbJar is contained in an application + webservices endpoints, a
     * DummyWebApp is created to hold "facade" servlet managing SOAP processing.
     *
     * @return an EjbJar or an Application Archive
     *
     * @throws GenBaseException When generation or storing fails
     */
    public Archive modify() throws GenBaseException {

        getLogger().log(BasicLevel.INFO, "Processing EjbJar " + ejbjar.getName());

        // Update MANIFEST with Version Number
        // used to say if WsGen has already been applied to this Module
        Attributes main = this.ejbjar.getManifest().getMainAttributes();
        main.put(new Attributes.Name(WsGenModifierConstants.WSGEN_JONAS_VERSION_ATTR), Version.getNumber());

        GeneratorFactory gf = GeneratorFactory.getInstance();
        Document jejbjar = ejbjar.getJonasEjbJarDoc();

        // Webservices endpoint
        List sds = ejbjar.getServiceDescs();

        if (sds.size() != 0) {
            if (ejbjar.getApplication() == null) {
                // we have webservices outside of an application

                /**
                 * Process : - create a default Application - add EjbJar within -
                 * return ApplicationModifier.modify()
                 */
                String ejbName = ejbjar.getRootFile().getName();
                String earName = ejbName.substring(0, ejbName.length() - ".jar".length()) + ".ear";
                Application application = new DummyApplication(earName);
                ejbjar.setApplication(application);
                application.addEjbJar(ejbjar);
                ApplicationModifier am = new ApplicationModifier(application);

                return am.modify();

            } else {
                // we have webservices inside of an application

                /**
                 * Process : - create a default WebApp - add in Application -
                 * iterate over the services - add files in web instead of
                 * ejbjar
                 */

                String warName = null;
                String war = ejbjar.getWarName();
                if (war != null) {
                    warName = war;
                } else {
                    String ejbName = ejbjar.getRootFile().getName();
                    String contextName = ejbName.substring(0, ejbName.length() - ".jar".length());
                    warName = contextName + ".war";
                }

                Application application = ejbjar.getApplication();
                WebApp web = new DummyWebApp(application, warName);

                for (Iterator i = sds.iterator(); i.hasNext();) {
                    ServiceDesc sd = (ServiceDesc) i.next();

                    // create dd modifier
                    WsEndpointDDModifier ddm = new WsEndpointDDModifier(web.getWebAppDoc());

                    // launch generation
                    Generator g = gf.newGenerator(sd, ddm, null, ejbjar);
                    g.generate();
                    g.compile();
                    // add files in web archive
                    g.addFiles(web);

                    //Now generate the security for the web app
                    Document context = web.getContextDoc();
                    if (context == null) {
                        context = web.newContextDoc();
                    }
                    ContextDDModifier cddm = new ContextDDModifier(context);
                    Document webJetty = web.getWebJettyDoc();
                    if (webJetty == null) {
                        webJetty = web.newWebJettyDoc();
                    }
                    WebJettyDDModifier wjddm = new WebJettyDDModifier(webJetty);
                    Document jonaswebservices = ejbjar.getJonasWebservicesDoc();
                    SecurityGenerator  sm = new SecurityGenerator(jonaswebservices);
                    sm.generate(ddm, cddm, wjddm);


                }
                // save webapp
                application.addWebApp(new WebApp(save(gf.getConfiguration(),
                        "webapps" + File.separator + web.getName(), web)), ejbjar.getContextRoot());
            }
        }

        // add client files
        List ejbs = ejbjar.getEjbs();
        for (Iterator i = ejbs.iterator(); i.hasNext();) {
            Ejb ejb = (Ejb) i.next();
            List refs = ejb.getServiceRefDescs();
            for (Iterator j = refs.iterator(); j.hasNext();) {
                ServiceRefDesc ref = (ServiceRefDesc) j.next();

                // create dd modifier
                WsClientDDModifier ddm = new WsClientDDModifier(ref.getServiceRefName(), jejbjar, ejb.getJonasBeanElement());

                // launch generation
                Generator g = gf.newGenerator(ref, ddm, ejbjar);
                g.generate();
                g.compile();
                // add files in web archive
                g.addFiles(ejbjar);
            }
        }

        return save(gf.getConfiguration(), "ejbjars" + File.separator + ejbjar.getRootFile().getName());

    }
}