package org.netbeans.lib.cvsclient.progress.receiving;

import java.util.*;

import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.file.*;
import org.netbeans.lib.cvsclient.progress.*;
import org.netbeans.lib.cvsclient.util.*;

/**
 * @author Thomas Singer
 */
public final class FileInfoAndMessageResponseProgressHandler
		implements ICvsListener, IMessageListener, IFileInfoListener {

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

	private final ResponseProgressHandler responseProgressHandler;
	private final String examiningDirectoryPattern;

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

	public static ICvsListener createInstance(IProgressViewer progressViewer, ICvsFiles cvsFiles, String examiningDirectoryPattern) {
		final Collection<FsFilePath> fsFiles = ResponseProgressHandler.getFsFiles(cvsFiles);
		return new FileInfoAndMessageResponseProgressHandler(examiningDirectoryPattern, fsFiles, progressViewer);
	}

	private FileInfoAndMessageResponseProgressHandler(String examiningDirectoryPattern, Collection<FsFilePath> fsFiles, IProgressViewer progressViewer) {
		BugLog.assertNotNull(examiningDirectoryPattern);
		BugLog.assertNotNull(fsFiles);
		BugLog.assertNotNull(progressViewer);

		this.examiningDirectoryPattern = examiningDirectoryPattern;
		this.responseProgressHandler = new ResponseProgressHandler(progressViewer, fsFiles);
	}

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

	public void registerListeners(ICvsListenerRegistry listenerRegistry) {
		listenerRegistry.addMessageListener(this);
		listenerRegistry.addFileInfoListener(this);
	}

	public void unregisterListeners(ICvsListenerRegistry listenerRegistry) {
		listenerRegistry.removeMessageListener(this);
		listenerRegistry.removeFileInfoListener(this);
	}

	public void messageSent(String message, boolean error, boolean tagged) {
		if (!error || tagged) {
			return;
		}

		final String directoryPath = CommandUtils.getExaminedDirectory(message, examiningDirectoryPattern);
		if (directoryPath == null) {
			return;
		}

		responseProgressHandler.directoryProcessed(FsPathUtils.unixDirectoryPathToFsFile(directoryPath));
	}

	public void fileInfoGenerated(Object info) {
		if (info instanceof IFileInfo) {
			final IFileInfo fileInfo = (IFileInfo)info;
			responseProgressHandler.fileProcessed(fileInfo.getFsFile());
		}
	}
}
