/*
 * @(#)FtpFileFilter.java
 *
 * Copyright (c) 2004 JSCAPE
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JSCAPE. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with JSCAPE.
 */
package com.jscape.inet.ftp;

import java.util.Vector;

/**
 * Utility class applies a filter to a set of FtpFile instances.
 */
public class FtpFileFilter {

    private static final String ALL = "*";

    private final String filter;

    /**
     * Constructs a new FtpFileFilter instance
     *
     * @param filter the filter to use
     */
    public FtpFileFilter(String filter) {
        this.filter = (filter.length() != 0) ? filter : ALL;
    }

    /**
     * Filters ftp files by name.
     *
     * @param files a Vector of FtpFile
     *
     * @return filtered files
     *
     * @see com.jscape.inet.ftp.FtpFile
     */
    @SuppressWarnings("unchecked")
    public Vector applyTo(Vector files) {
        Vector result = new Vector();

        for (int i = 0; i < files.size(); ++i) {
            FtpFile file = (FtpFile) files.elementAt(i);

            if (matches(file.getFilename())) {
                result.addElement(file);
            }
        }
        return result;
    }

    /**
     * Checks if filename matches filter
     *
     * @param filename the filename to test
     *
     * @return true if filter matches, false otherwise
     */
    private boolean matches(String filename) {
        int allPos = this.filter.indexOf(ALL);

        if (allPos != -1) {
            String beginFilter = this.filter.substring(0, allPos);
            String endFilter = this.filter.substring(allPos + ALL.length());
            return (filename.startsWith(beginFilter) && filename.endsWith(endFilter));
        }

        return filename.equals(this.filter);
    }

}
