/*
 * 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 com.arsdigita.bebop.Component;
import com.arsdigita.bebop.Container;
import com.arsdigita.bebop.Label;
import org.apache.log4j.Logger;

/**
 * Tag for defining a Bebop container in a JSP.
 */
public abstract class DefineContainer extends DefineComponent {
    public static final String versionId = "$Id: //core-platform/dev/src/com/arsdigita/bebop/jsp/DefineContainer.java#11 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";

    private static final Logger s_log =
        Logger.getLogger(DefineComponent.class.getName());

    /**
     * If we have text intervening between tags, then we turn it into
     * a Bebop Label object so it becomes part of the Page's component
     * hierarchy.
     * <p>
     * doAfterBody would be called by the JSP container at the end
     * of a tag, but we call it from ContainerTag.doStartTag() manually
     * so we get the text here in several discrete chunks separated
     * by our child component tags, instead of in one big chunk at the
     * end.
     */
    public int doAfterBody() {
        if (bodyContent == null) {
            return SKIP_BODY;
        }

        String body = bodyContent.getString();
        if (body != null && body.trim().length() > 0) {
            // create new Label object
            // with output escaping disabled, so that you can
            // put badly-formed HTML in your JSP pages.
            // (the other option is to parse $body as XML.)
            Label l = new Label(body, false);

            // now find our parent object and put it in.
            this.addComponent(l);

            try {
                bodyContent.clear();
            } catch (java.io.IOException ioe) {
                try {
                    pageContext.handlePageException(ioe);
                } catch (Exception nested) {
                    s_log.error("error serving error page", nested);
                }
                throw new JspWrapperException(ioe);
            }
        }
        return SKIP_BODY;
    }

    /**
     * adds a component to the container represented by this tag.
     */
    public void addComponent(Component c) {
        ((Container)this.getComponent()).add(c);
    }
}
