/*
 * Copyright (C) 2004 TiongHiang Lee
 *
 * 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 (at your option) 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
 *
 * Email: thlee@onemindsoft.org
 */

package org.onemind.jxp;

import java.io.Writer;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.onemind.commons.java.datastructure.NametableStack;
import org.onemind.commons.java.lang.reflect.ClassLookupCache;
import org.onemind.jxp.util.StaticImport;
/**
 * An processing context contains everything specific to a specific execution of an JxpPage so that there's only one parser needed
 * for all the processings
 * @author TiongHiang Lee (thlee@onemindsoft.org)
 * 
 */
class JxpProcessingContext
{

    /** the logger * */
    private static final Logger _logger = Logger.getLogger(JxpProcessingContext.class.getName());

    /** default imports * */
    private static final ClassLookupCache _default_imports = new ClassLookupCache();
    static
    {
        _default_imports.addImport("*");
        _default_imports.addImport("java.lang.*");
        _default_imports.addImport("java.util.*");
    }

    private static final String KEY_SCRIPT_NAME = "jxp_script_name";

    private static final String KEY_WRITER = "jxp_writer";

    private static final String KEY_CONTEXT = "jxp_context";

    /** the imports * */
    private ClassLookupCache _imports = new ClassLookupCache();

    /** the writer * */
    private Writer _writer;

    /** the stack of pages in current processing context * */
    private Stack _pageStack = new Stack();

    /** the nametable scope stack **/
    private Stack _ntStack = new Stack();

    /** the current page **/
    private JxpPage _currentPage;

    /** the name tables * */
    private NametableStack _nametableStack;

    /** the functions map **/
    private Map _userDefinedFunctions = new HashMap();

    /** the static imports **/
    private List _staticImports = new ArrayList();

    /**
     * {@inheritDoc}
     */
    public JxpProcessingContext(Writer writer, Map env)
    {
        _writer = writer;
        env.put(KEY_WRITER, _writer);
        env.put(KEY_CONTEXT, this);
        _nametableStack = new NametableStack(env);
    };

    /**
     * Push current page to the page stack
     * @param page the page
     */
    public final void pushPage(JxpPage page)
    {
        _currentPage = page;
        _pageStack.push(page);
        if (_nametableStack.containsName(KEY_SCRIPT_NAME))
        {
            _nametableStack.assign(KEY_SCRIPT_NAME, page.getName());
        } else
        {
            _nametableStack.declare(KEY_SCRIPT_NAME, page.getName());
        }
    }

    /**
     * Get the current page
     * @return the current page
     */
    public final JxpPage getCurrentPage()
    {
        return _currentPage;
    }

    /**
     * Pop the current page
     * @param page the current page
     * @throws IllegalStateException if the page is not current page
     */
    public final void popPage(JxpPage page) throws IllegalStateException
    {
        if (_pageStack.peek() != page)
        {
            throw new IllegalStateException("Popping wrong page " + page);
        } else
        {
            _pageStack.pop();
            if (_pageStack.size() != 0)
            {
                _currentPage = (JxpPage) _pageStack.peek();
            } else
            {
                _currentPage = null;
            }
            if (_currentPage!=null)
            {
                _nametableStack.assign(KEY_SCRIPT_NAME, _currentPage.getName());
            }
        }
    }

    /**
     * Resolve a class
     * @param className the class name
     * @return the class
     */
    protected final Class resolveClass(String className)
    {
        if (_logger.isLoggable(Level.FINEST))
        {
            _logger.finest("Resolving " + className);
        }
        Class c = _default_imports.getClass(className);
        if (c == null)
        {
            if (_logger.isLoggable(Level.FINEST))
            {
                _logger.finest("Resolving " + className + " package " + _imports.getPackages());
            }
            c = _imports.getClass(className);
        }
        return c;
    }

    /**
     * Return the name table stack
     * @return the name table stack
     */
    public final NametableStack getNametableStack()
    {
        return _nametableStack;
    }

    /**
     * Return the imports
     * @return the imports
     */
    public final ClassLookupCache getImports()
    {
        return _imports;
    }

    /**
     * Get the writer
     * @return the writer
     */
    public final Writer getWriter()
    {
        return _writer;
    }

    /**
     * Return the functions
     * @return the functions.
     */
    public final Map getUserDefinedFunctions()
    {
        return _userDefinedFunctions;
    }

    /**
     * Add static import
     * @param sImport the static import to add
     */
    public void addStaticImport(StaticImport sImport)
    {
        _staticImports.add(sImport);
    }

    /**
     * Get static imports
     * @return the static imports
     */
    public final List getStaticImports()
    {
        return _staticImports;
    }
}