/*
 * Copyright (C) 2002-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.formbuilder.ui.jsp;

import com.arsdigita.bebop.MetaForm;
import com.arsdigita.bebop.Form;
import com.arsdigita.util.UncheckedWrapperException;
import com.arsdigita.bebop.PageState;
import com.arsdigita.formbuilder.ui.BaseAddObserver;
import com.arsdigita.formbuilder.ui.PlaceholdersInitListener;
import com.arsdigita.formbuilder.util.Placeholders;
import java.util.HashMap;
import java.util.Iterator;
import com.arsdigita.formbuilder.PersistentForm;



public abstract class JspForm extends MetaForm {
    private HashMap m_vars;

    public JspForm(String name) {
        super(name);

        m_vars = new HashMap();
    }

    public Form buildForm(PageState state) {
        try {
            PersistentForm f = getPersistentForm();
            f.setComponentAddObserver(new BaseAddObserver());

            Form form = (Form)f.createComponent();
            form.addInitListener(new JSPInitListener(m_vars));
            return form;
        } catch (FormNotFoundException ex) {
            throw new UncheckedWrapperException("Cannot find form", ex);
        }
    }

    public abstract PersistentForm getPersistentForm()
        throws FormNotFoundException;

    public void setVariable(String name,
                            String value) {
        m_vars.put(name, value);
    }

    private class JSPInitListener extends PlaceholdersInitListener {
        HashMap m_vars;

        public JSPInitListener(HashMap vars) {
            m_vars = vars;
        }

        protected Placeholders getPlaceholders(PageState state) {
            Placeholders p = super.getPlaceholders(state);

            Iterator i = m_vars.keySet().iterator();
            while (i.hasNext()) {
                String key = (String)i.next();
                String value = (String)m_vars.get(key);

                p.setVariable("jsp." + key, value);
            }
            return p;
        }
    }
}
