/*
 * 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.cms.ui.util;

import com.arsdigita.bebop.FormProcessException;
import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.event.FormSectionEvent;
import com.arsdigita.bebop.event.FormValidationListener;
import com.arsdigita.bebop.form.Widget;


/**
 * Validates that the string value of the widget is unique.
 *
 * @author Michael Pih (pihman@arsdigita.com)
 * @version $Revision: #5 $ $DateTime: 2004/04/07 16:07:11 $
 */
public abstract class UniqueStringValidationListener
    implements FormValidationListener {

    public static final String versionId = "$Id: //cms/dev/src/com/arsdigita/cms/ui/util/UniqueStringValidationListener.java#5 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";

    private final static String ERROR_MSG =
        "Unique string value constraint violation.";

    private Widget m_widget;
    private String m_errorMsg;


    /**
     * Private constructor.
     */
    private UniqueStringValidationListener() {}

    /**
     * Constructor.
     */
    public UniqueStringValidationListener(Widget widget) {
        this(widget, null);
    }

    /**
     * Constructor.
     *
     * @param widget The form widget
     * @param errorMsg An error message
     * @pre ( widget != null )
     */
    public UniqueStringValidationListener(Widget widget, String errorMsg) {
        m_widget = widget;

        if ( errorMsg == null ) {
            m_errorMsg = ERROR_MSG;
        } else {
            m_errorMsg = errorMsg;
        }
    }

    /**
     * Ensure that the name of the item is unique by resolving the
     * would-be URL of the item. If an item "exists" at the URL already,
     * then the name is invalid.
     *
     * @param event The form section event
     * @pre ( event != null )
     */
    public final void validate(FormSectionEvent event)
        throws FormProcessException {

        PageState state = event.getPageState();

        String value = (String) m_widget.getValue(state);

        if ( !isUnique(state, value) ) {
            throw new FormProcessException(m_errorMsg);
        }

    }

    /**
     * Returns true if the string value is unique, false otherwise.
     *
     * @param state The page state
     * @param value The submitted string value
     * @return true if the string value is unique, false otherwise
     */
    protected abstract boolean isUnique(PageState state, String value);

}
