/*
 * 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 javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 * Base class for instantiating Bebop components with JSP tags.  A
 * Bebop component declaration will always add the created component
 * to the container defined by the containing (parent) tag.   Intervening
 * text in the JSP (e.g., &lt;bebop:form>form label &lt;bebop:widget/>...)
 * is turned into Label objects.
 */

public abstract class DefineComponent extends BodyTagSupport {
    private String m_name;

    private final static String CONTAINER_ERROR =
        "define:component must be contained within a container definition.";

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

    public int doStartTag() throws JspException {
        if (getName() != null) {
            pageContext.setAttribute(getName(), getComponent());
        }
        // set all components ID
        getComponent().setIdAttr(getName());

        // nearly always, a componentTag will be contained within
        // another tag.  So we want make any intervening text
        // be treated as child Label of that container, and add the
        // component that this ComponentTag declares to the parent
        // container.
        // (PageTag is an exception.)
        getParentTag().doAfterBody();
        getParentTag().addComponent(getComponent());
        return EVAL_BODY_TAG;
    }

    protected DefineContainer getParentTag() throws JspException {
        if (this.getParent() instanceof DefineContainer) {
            return (DefineContainer)this.getParent();
        } else {
            throw new JspException(CONTAINER_ERROR);
        }
    }

    protected abstract Component getComponent();

    public final String getName() {
        return m_name;
    }

    public final void setName(String s) {
        m_name = s;
    }
}
