/*
 * 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.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * tag for including the contents of a slave page within the
 * result page's current output context.
 */
public class ShowSlave extends ShowComponent {

    public static final String versionId = "$Id: //core-platform/dev/src/com/arsdigita/bebop/jsp/ShowSlave.java#7 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";
    public int doEndTag() throws JspException {
        com.arsdigita.xml.Document wrapper =
            (com.arsdigita.xml.Document)pageContext.getRequest()
            .getAttribute(SLAVE_DOC);
        if (wrapper == null) {
            throw new JspException("Cannot use slave tag except in master page");
        }
        Document doc = wrapper.getInternalDocument();
        Element topLevel = doc.getDocumentElement();
        ShowContainer parent = getContainerTag();
        // topLevel is
        // <bebop:page>
        //   <bebop:title/>
        //   [stuff we want to add]
        // </bebop:page>
        NodeList children = topLevel.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (i > 0 || !child.getNodeName().equals("bebop:title")) {
                Node toAdd = getResultDocument().importNode(child, true);
                parent.getOutputContext().appendChild(toAdd);
            }
        }
        return EVAL_PAGE;
    }
}
