/**
 * JOnAS : Java(TM) OpenSource Application Server
 *
 * 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
 *
 * Initial Developer : Guillaume Sauthier
 * --------------------------------------------------------------------------
 * $Id: JVelocity.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.generators.wsgen.generator.axis;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.ow2.jonas.generators.wsgen.WsGenException;
import org.ow2.jonas.lib.util.I18n;
import org.ow2.jonas.lib.util.Log;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;




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

/**
 * Wrapper around Velocity tool.
 *
 * @author Guillaume Sauthier
 */
public class JVelocity {

    /** i18n */
    private static I18n i18n = I18n.getInstance(JVelocity.class);

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

    /** Velocity Engine */
    private VelocityEngine vEngine;

    /** Velocity Template */
    private Template template;

    /**
     * Creates a new JVelocity instance using the given template.
     *
     * @param tmplName the template filename
     *
     * @exception WsGenException when error occurs during Velocity
     *            initialization.
     */
    public JVelocity(String tmplName) throws WsGenException {
        // Prepare Velocity Engine
        String jonasRoot = System.getProperty("jonas.root");

        if (jonasRoot == null) {
            String err = i18n.getMessage("JVelocity.constr.notset");
            throw new WsGenException(err);
        }

        //String path2Tmpl = new String(jonasRoot + File.separatorChar + "templates" + File.separatorChar + "wsgen"
        //        + File.separatorChar + "generator" + File.separatorChar + "axis");

        // instanciate the engine
        vEngine = new VelocityEngine();
        //vEngine.setProperty(RuntimeConstants.VM_LIBRARY, "");
        vEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
        //vEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, path2Tmpl);

        try {
            vEngine.init();
        } catch (Exception e) {
            String err = i18n.getMessage("JVelocity.constr.initFailure");
            throw new WsGenException(err, e);
        }

        // Create the Template
        try {
            template = vEngine.getTemplate(tmplName);
        } catch (Exception e) {
            String err = i18n.getMessage("JVelocity.constr.tmplError", tmplName);
            throw new WsGenException(err, e);
        }
    }

    /**
     * Generate the given file with the given VelocityContext.
     *
     * @param fs the output file
     * @param context VelocityContext
     *
     * @throws WsGenException when velocity generation fails
     */
    public void generate(File fs, VelocityContext context) throws WsGenException {
        FileWriter fwriter = null;

        try {
            // Create before the parent directory
            File fdir = fs.getParentFile();

            if (fdir != null) {
                if (!fdir.exists()) {
                    if (!fdir.mkdirs()) {
                        String err = i18n.getMessage("JVelocity.generate.directories", fdir.getPath());
                        throw new WsGenException(err);
                    }
                }
            }

            fwriter = new FileWriter(fs);
        } catch (IOException e) {
            String err = i18n.getMessage("JVelocity.generate.file", fs);
            throw new WsGenException(err, e);
        }

        try {
            template.merge(context, fwriter);
        } catch (Exception e) {
            String err = i18n.getMessage("JVelocity.generate.cannot", fs);
            throw new WsGenException(err, e);
        }

        try {
            fwriter.flush();
            fwriter.close();
        } catch (IOException e) {
            // do nothing, just a warn
            String err = i18n.getMessage("JVelocity.generate.close", fs);
            logger.log(BasicLevel.WARN, err);
        }
    }
}