package tasks.bench;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import data.BuildInfo;
import data.BuildType;
import tasks.util.Exec;

public class FindBuildType {

	private final File projectDir;
	private final BuildInfo buildInfo;

	public FindBuildType(File projectDir) {
		this.projectDir = projectDir;
		this.buildInfo = new BuildInfo();
	}

	public BuildInfo findBuildType() {
		findBuildInfo();
		return buildInfo;
	}

	private void findBuildInfo() {
		addBuildFiles(getBuildFiles("AndroidManifest.xml"), BuildType.ANDROID);
		addBuildFiles(getBuildFiles("pom.xml"), BuildType.MAVEN);
		addBuildFiles(getBuildFiles("build.gradle"), BuildType.GRADLE);
		addBuildFiles(getBuildFiles("build.xml"), BuildType.ANT);
		addBuildFiles(getBuildFiles(".classpath"), BuildType.ECLIPSE);
		addBuildFiles(getBuildFiles(".idea"), BuildType.INTELLIJ);
	}

	private Set<File> getBuildFiles(String buildFileName) {
		Set<File> buildFiles = new HashSet<File>();

		List<String> res = Exec.exec("dir " + buildFileName + " /s", projectDir);
		if (res != null) {
			for (String line : res) {
				if (line.contains("Directory of")) {
					String[] parts = line.split(" ");
					String path = parts[parts.length - 1];
					File buildFile = new File(path + File.separator + buildFileName);
					if (buildFile.exists())
						buildFiles.add(buildFile);
				}
			}
		}
		return buildFiles;
	}

	private void addBuildFiles(Set<File> buildFiles, BuildType buildType) {
		if (buildFiles != null && !buildFiles.isEmpty()) {
			Set<File> newBuildFiles = new HashSet<File>();
			for (File f : buildFiles) {
				if (!isInSubDirOf(buildFiles, f)) {
					newBuildFiles.add(f);
				}
			}
			buildInfo.potentialBuildTypes.put(buildType, newBuildFiles);
		}
	}

	private boolean isInSubDirOf(Set<File> set, File file) {
		for (File f : set) {
			if (file == f)
				continue;
			String pathFile = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf(File.separator));
			String pathf = f.getAbsolutePath().substring(0, f.getAbsolutePath().lastIndexOf(File.separator));
			if (pathFile.contains(pathf))
				return true;
		}
		return false;
	}

}
