/**
 * JOnAS: Java(TM) Open 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.genclientstub.modifier;

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

import org.ow2.jonas.deployment.api.IEJBRefDesc;
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.genclientstub.generator.Generator;
import org.ow2.jonas.generators.genclientstub.generator.GeneratorFactory;


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

/**
 * Modify a given WebApp.
 *
 * @author Guillaume Sauthier
 */
public class WebAppModifier extends AbsArchiveModifier {

    /** webapp */
    private WebApp web;

    /**
     * Creates a new WebAppModifier
     *
     * @param webapp
     *            the WebApp J2EE archive
     */
    public WebAppModifier(WebApp webapp) {
        super(webapp);
        web = webapp;
    }

    /**
     * Modify the current archive and return a modified archive.
     *
     * @return a modified archive.
     *
     * @throws GenBaseException
     *             When modification fails
     */
    public Archive modify() throws GenBaseException {

        getLogger().log(BasicLevel.INFO, "Processing WebApp " + web.getName());

        GeneratorFactory gf = GeneratorFactory.getInstance();

        // Found automatically the stubs
        generateFoundStubs(gf.getConfiguration(), web);

        // Ejb-Ref
        List ejbRefs = web.getEjbRefDescs();
        for (Iterator j = ejbRefs.iterator(); j.hasNext();) {
            IEJBRefDesc ejbRef = (IEJBRefDesc) j.next();

            // launch generation
            Generator g = new Generator(gf.getConfiguration(), ejbRef, null, web);
            g.generate();
            g.compile();
            // add files in web archive
            g.addFiles(web);
        }

        return save(gf.getConfiguration(), "webapps" + File.separator
                + web.getName());
    }
}