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

import com.arsdigita.bebop.event.ParameterEvent;
import com.arsdigita.bebop.event.ParameterListener;
import com.arsdigita.bebop.parameters.ParameterData;
import org.apache.log4j.Logger;

import java.util.StringTokenizer;

/**
 * Verifies that the parameter is a valid filename, is not null, and
 * contains no reserved characters.
 *
 * @author Justin Ross &lt;jross@redhat.com&gt;
 * @version $Id: //cms/dev/src/com/arsdigita/cms/ui/authoring/NameValidationListener.java#7 $
 */
public class NameValidationListener implements ParameterListener {
    public static final String versionId = 
        "$Id: //cms/dev/src/com/arsdigita/cms/ui/authoring/NameValidationListener.java#7 $" +
        "$Author: dennis $" +
        "$DateTime: 2004/04/07 16:07:11 $";

    private static final Logger s_log = Logger.getLogger
        (NameValidationListener.class);

    // Why is this protected? XXX
    protected String label;

    // XXX this stuff needs globalization

    /**
     * Constructs a new <code>NameValidationListener</code>.
     *
     * @param label the label for the error message
     */
    public NameValidationListener(final String label) {
        this.label = label;
    }

    /**
     * Constructs a new <code>NameValidationListener</code>.
     */
    public NameValidationListener() {
        this("This parameter");
    }

    public void validate(final ParameterEvent e) {
        final ParameterData data = e.getParameterData();
        final Object value = data.getValue();

        if (value == null || value.toString().length() < 1) {
            data.addError(label + " may not be null");
            return;
        }

        final String text = value.toString();

        final StringTokenizer tok =
            new StringTokenizer(text, "*? /\\\'\"&$`~");

        if (tok.hasMoreTokens()) {
            final String token = tok.nextToken();

            if (!token.equals(text)) {
                data.addError(label + " should be a valid filename");
            }
        }

        if (text.indexOf(".") != -1) {
            data.addError(label + " may not contain periods");
        }
    }
}
