package tasks.bench;

import java.util.HashSet;
import java.util.Set;

/**
 * Queries issues statistics (if there is was at least a commit in the last
 * year)
 * 
 * @author Lisa Nguyen Quang Do
 */

public class LibrariesFilter {

	public Set<String> getCommonLibraries(Set<String> libraries, Set<String> whitelist) {
		Set<String> ret = new HashSet<String>();
		for (String lib : libraries)
			if (containsAnotherVersion(whitelist, lib))
				ret.add(lib);
		return ret;
	}

	public boolean containsAnotherVersion(Set<String> libs, String l) {
		for (String lib : libs) {
			if (lib == null || lib.equals("") || lib.equals(" "))
				continue;
			String prefix1 = getLongestPrefix(lib);
			String prefix2 = getLongestPrefix(l);
			if (prefix1.equals(prefix2))
				return true;
		}
		return false;
	}

	private String getLongestPrefix(String lib) {
		int dotPos = lib.lastIndexOf(".");
		int dashPos = lib.lastIndexOf("-");
		int colonPos = lib.indexOf(":");
		if (dashPos < 0 && colonPos < 0) {
			if (dotPos < 0)
				return lib;
			return lib.substring(0, dotPos);
		} else {
			int max = Math.max(dashPos, colonPos);
			return lib.substring(0, max);
		}
	}

}
