/*
 * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.bebop.jsp;

import javax.servlet.jsp.JspException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.TreeWalker;

/**
 * tag for displaying a Bebop form and widgets within it.
 * A Bebop form is a special case of a container because we need to
 * preserve the pageState children which will later turn into
 * &lt;input type=hidden>.
 */
public class ShowForm extends ShowContainer {

    public static final String versionId = "$Id: //core-platform/dev/src/com/arsdigita/bebop/jsp/ShowForm.java#9 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";
    private Node m_oldOutputContext;
    private Node m_formResult;

    public int doStartTag() throws JspException {
        super.doStartTag();
        // shallow-copy bebop:form into new document
        m_formResult =
            getResultDocument().importNode(getInputContext(), false);
        // now copy all bebop:pageState children into formResult
        TreeWalker walker = createTreeWalker(new NodeFilter() {
                public short acceptNode(Node n) {
                    String nodeName = n.getNodeName();
                    if (nodeName.equals("bebop:pageState")) {
                        return FILTER_ACCEPT;
                    }
                    if (nodeName.equals("bebop:formWidget")) {
                        if (((Element)n).getAttribute("type").equals("hidden")) {
                            return FILTER_ACCEPT;
                        }
                    }
                    return FILTER_SKIP;
                }
            });
        Node n;
        while ((n = walker.nextNode()) != null) {
            Node resultNode = getResultDocument().importNode(n, true);
            m_formResult.appendChild(resultNode);
        }
        m_oldOutputContext = getOutputContext();
        setOutputContext(m_formResult);
        return EVAL_BODY_TAG;
    }

    public int doEndTag() throws JspException {
        setOutputContext(m_oldOutputContext);
        if (!isEmpty()) {
            getOutputContext().appendChild(m_formResult);
            return EVAL_PAGE;
        } else {
            return super.doEndTag();
        }
    }
}
