/*
 * 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.formbuilder.util.GlobalizationUtil ; 

import com.arsdigita.formbuilder.ComponentAddObserver;
import com.arsdigita.bebop.FormSection;
import com.arsdigita.formbuilder.PersistentComponentFactory;
import com.arsdigita.formbuilder.PersistentSubmit;
import com.arsdigita.formbuilder.PersistentText;
import com.arsdigita.formbuilder.CompoundComponent;
import com.arsdigita.bebop.Component;
import com.arsdigita.bebop.ColumnPanel;
import com.arsdigita.bebop.Label;


/**
 * This class provides a basic implementation of the
 * {@link com.arsdigita.formbuilder.ComponentAddObserver}
 * class which will organise a sensible layout for
 * controls on a form
 */
public class BaseAddObserver implements ComponentAddObserver {

    public void beforeAddingComponent(FormSection formSection,
                                      PersistentComponentFactory componentFactory,
                                      int componentPosition) {
        // Padding
        if (componentFactory instanceof PersistentSubmit ||
            componentFactory instanceof PersistentText) {
            formSection.add(new Label(""));
        }

        // Make sure we process nested form sections
        try {
            CompoundComponent fs = (CompoundComponent)componentFactory;
            fs.setComponentAddObserver(new BaseAddObserver());
        } catch (ClassCastException ex) {
            // Nada
        }
    }

    public void addingComponent(PersistentComponentFactory componentFactory,
                                int componentPosition,
                                Component component) {
        // Nada
    }

    public void afterAddingComponent(FormSection formSection,
                                     PersistentComponentFactory componentFactory,
                                     int componentPosition) {

        if (componentFactory instanceof CompoundComponent) {
            try {
                ColumnPanel panel = (ColumnPanel)formSection.getPanel();

                FormSection fs = (FormSection)formSection.get(formSection.size()-1);
                panel.setConstraint(fs, ColumnPanel.FULL_WIDTH);
            } catch (ClassCastException ex) {
                // Nada
            }
        }
    }
}
