/*
 * 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.bebop.parameters;

import com.arsdigita.bebop.FormProcessException;
import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.RequestLocal;
import com.arsdigita.bebop.event.ParameterEvent;
import com.arsdigita.bebop.event.ParameterListener;

/**
 * A generic validation listener that wraps any parameter listener so
 * that the parameter listener is conditionally run based on the value
 * of a RequestLocal. The constructor takes in a parameter listener
 * and a RequestLocal that returns a Boolean. The request local is
 * lazily evaluated when the validation listener is run. A typical
 * code block for the request local:
 *
 * <pre>
 *     private RequestLocal m_isCancel = new RequestLocal() {
 *       public Object initialValue(PageState ps) {
 *           if ( m_submit.isSelected(ps) ) {
 *                return Boolean.FALSE;
 *           } else {
 *               return Boolean.TRUE;
 *           }
 *       }};
 * </pre>
 *
 * Which only returns false if the main submit button is selected.
 *
 *
 */
public class CancellableValidationListener implements ParameterListener {

    private RequestLocal m_isCancel;
    private GlobalizedParameterListener m_listener;

    /**
     *
     * @parameter l The listener that should be fired if this is not a
     * cancel event.
     * @parameter isCancel a Boolean RequestLocal that is true if this
     * is a cancel event; otherwise false.
     *  */
    public CancellableValidationListener(GlobalizedParameterListener l,
                                         RequestLocal isCancel) {
        m_isCancel = isCancel;
        m_listener = l;
    }

    public void validate(ParameterEvent evt) throws FormProcessException {
        PageState ps = evt.getPageState();
        Boolean b = (Boolean) m_isCancel.get(ps);

        if ( b == Boolean.TRUE ) {
            return;
        } else {
            m_listener.validate(evt);
        }

    }

}
