/*
 *                 Sun Public License Notice
 *
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 *
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
 * Microsystems, Inc. All Rights Reserved.
 */
package org.netbeans.lib.cvsclient.command;

import java.io.*;
import java.util.*;

import org.netbeans.lib.cvsclient.file.*;
import org.netbeans.lib.cvsclient.util.*;

/**
 * @author Thomas Singer
 */
final class CvsFiles
		implements ICvsFiles {

	// Fields =================================================================

	private final List<CvsFile> cvsFiles = new ArrayList<CvsFile>();
	private CvsFile currentCvsDirectory;

	// Setup ==================================================================

	public CvsFiles() {
	}

	// Implemented ============================================================

	public void visitFilesAndDirectories(ICvsFilesDirectoriesVisitor visitor) throws IOException, CommandAbortedException {
		BugLog.assertNotNull(visitor);

		for (final CvsFile cvsFile : cvsFiles) {
			if (cvsFile.isDirectory()) {
				visitor.handleDirectory((FsDirectoryPath)cvsFile.getFsEntry());
			}
			else {
				visitor.handleFile((FsFilePath)cvsFile.getFsEntry(), cvsFile.getEntry(), cvsFile.exists());
			}
		}
	}

	public void visitFiles(ICvsFilesVisitor visitor) throws CommandAbortedException, IOException {
		BugLog.assertNotNull(visitor);

		for (final CvsFile cvsFile : cvsFiles) {
			if (!cvsFile.isDirectory()) {
				visitor.handleFile((FsFilePath)cvsFile.getFsEntry(), cvsFile.getEntry(), cvsFile.exists());
			}
		}
	}

	// Actions ================================================================

	public void add(CvsFile cvsFile) {
		if (currentCvsDirectory == null) {
			BugLog.assertTrue(cvsFile.isDirectory(), "The first cvsFile must be a directory.");

			currentCvsDirectory = cvsFile;
		}
		else {
			if (cvsFile.isDirectory()) {
				if (currentCvsDirectory.getFsEntry().getPath().equals(cvsFile.getFsEntry().getPath())) {
					// do not add the same directory twice
					return;
				}

				currentCvsDirectory = cvsFile;
			}
		}
		cvsFiles.add(cvsFile);
	}
}
