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

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

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

/**
 * @author Thomas Singer
 */
public final class FileStateRequestsProgressHandler
		implements IRequestsProgressHandler {

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

	private final Set<FsFilePath> fsFiles = new HashSet<FsFilePath>(2000);
	private final IProgressViewer progressViewer;
	private final int maxCount;
	private int count;

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

	public FileStateRequestsProgressHandler(IProgressViewer progressViewer, ICvsFiles cvsFiles) {
		BugLog.assertNotNull(progressViewer);
		BugLog.assertNotNull(cvsFiles);

		this.progressViewer = progressViewer;

		try {
			cvsFiles.visitFiles(new ICvsFilesVisitor() {
				public void handleFile(FsFilePath fsFile, Entry entry, boolean exists) {
					fsFiles.add(fsFile);
				}
			});
		}
		catch (CommandAbortedException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		count = 0;
		maxCount = fsFiles.size();
	}

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

	public void requestSent(IRequest request) {
		if (!(request instanceof AbstractFileStateRequest)) {
			return;
		}

		final AbstractFileStateRequest fileStateRequest = (AbstractFileStateRequest)request;
		final FsFilePath fsFile = fileStateRequest.getFsFile();
		if (!fsFiles.remove(fsFile)) {
			return;
		}

		count++;
		notifyProgress(count, maxCount, progressViewer);
	}

	// Utils ==================================================================

	private static void notifyProgress(int count, int maxCount, IProgressViewer progressViewer) {
		progressViewer.setProgress((double)count / maxCount);
	}
}
