/*
 * ScriptExpander.java  $Revision: 1.4 $  $Date: 2007/10/03 04:39:39 $
 *
 * Copyright (C) 2007 Meldcraft Corporation
 *
 * This file is part of Scaffold.
 * 
 * Scaffold 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 3 of the License, or
 * (at your option) any later version.
 * 
 * Scaffold 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 Scaffold.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.meldcraft.util;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleBindings;

/**
 * @version $Revision: 1.4 $ $Date: 2007/10/03 04:39:39 $
 * @author Rob Richards
 */
public class ScriptExpander extends AbstractStringExpander
{
    private Bindings        mBindings = new SimpleBindings();
    private ScriptEngine    mEngine;

    public ScriptExpander()
    {
        super("<script");

        String type = "JavaScript";
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName(type);
        engine.setBindings(getBindings(), ScriptContext.ENGINE_SCOPE);
        mEngine = engine;
    }

    public boolean expandScript(String str)
    {
        return expand(str);
    }

    public Bindings getBindings()
    {
        return mBindings;
    }

    @Override
    protected Object expandPart(String type, String part)
    {
        Object ret = null;
        try
        {
            /*
            if (StringUtil.isEmpty(type))
            {
                type = "JavaScript";
            }
            */
            if (part != null)
            {
                ret = mEngine.eval(part);
            }
        }
        catch (ScriptException e)
        {
            throw new RuntimeException("Error running expand script.", e);
        }
        return ret;
    }
}



