/*
 * 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;

import com.arsdigita.bebop.event.FormInitListener;
import com.arsdigita.bebop.event.FormSectionEvent;
import com.arsdigita.bebop.FormProcessException;
import com.arsdigita.bebop.Form;
import com.arsdigita.formbuilder.util.Placeholders;
import com.arsdigita.bebop.util.Traversal;
import com.arsdigita.bebop.Component;
import com.arsdigita.bebop.form.Widget;
import com.arsdigita.bebop.PageState;


public class PlaceholdersInitListener implements FormInitListener {

    public void init(FormSectionEvent e)
        throws FormProcessException {

        Form f = (Form)e.getSource();

        Placeholders placeholders = getPlaceholders(e.getPageState());

        PlaceholdersTraversal t = new PlaceholdersTraversal(placeholders, e.getPageState());
        t.preorder(f);
    }

    protected Placeholders getPlaceholders(PageState state) {
        return new Placeholders(state);
    }

    private class PlaceholdersTraversal extends Traversal {
        Placeholders m_placeholders;
        PageState m_state;

        public PlaceholdersTraversal(Placeholders placeholders,
                                     PageState state) {
            m_placeholders = placeholders;
            m_state = state;
        }

        public void act(Component c) {
            try {
                Widget w = (Widget)c;
                String value = (String)w.getParameterModel().getDefaultValue();
                if (value != null)
                    w.setValue(m_state, m_placeholders.interpolate(value));
            } catch (ClassCastException ex) {
                // Nada
            }
        }
    }
}
