buildscript {
	repositories {
		mavenCentral()
		maven { url "http://dl.bintray.com/jetbrains/intellij-plugin-service" }
	}
}
plugins {
	id "org.jetbrains.intellij" version "0.2.17"
}
apply plugin: "java"
apply plugin: "groovy"
apply plugin: "idea"

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
	mavenCentral()
	ivy {
		layout "pattern"
		artifactPattern "./lib/[organisation]-[artifact]-[revision](.[ext])"
	}
}
intellij {
	// (to find available IDE versions see https://www.jetbrains.com/intellij-repository/releases)
	def ideVersion = System.getenv().getOrDefault("IDEA_VERSION", "IU-172.3757.29")
	println("Using ide version: ${ideVersion}")
	version ideVersion
	pluginName = "CodeHistoryMining"
	downloadSources = true
	sameSinceUntilBuild = false
	updateSinceUntilBuild = false
	plugins = ["git4idea"]
}

dependencies {
	compile "org.codehaus.groovy:groovy:2.4.6"
	compile "org.codehaus.groovy:groovy-json:2.4.6"
    compile "codehistoryminer:core:1.0"
    compile "org.vcsreader:vcsreader:1.1.0"
    compile "org.apache.commons:commons-csv:1.0"
    compile "liveplugin:live-plugin:0.6.3 beta"
	compile "org.jetbrains:annotations-java5:15.0" // use java5 annotations because groovy can't compile java8 @NotNull annotations
}

sourceSets {
    main {
        java { srcDir "src/main" }
	    resources { srcDir "src/resources" }
    }
	test {
		java { srcDir "src/test" }
	}
}

task validatePluginZip() { doLast {
	def pluginZip = zipTree("build/distributions/CodeHistoryMining.zip")
	def pluginZipFiles = pluginZip.files.collect { it.path.replaceFirst(".*/CodeHistoryMining.zip.*?/", "") }.toSet()

	expectToBeEqual(pluginZipFiles, [
		"CodeHistoryMining/lib/groovy-2.4.6.jar",
		"CodeHistoryMining/lib/liveplugin-live-plugin-0.6.3 beta.jar",
		"CodeHistoryMining/lib/code-history-mining-plugin.jar",
		"CodeHistoryMining/lib/groovy-json-2.4.6.jar",
		"CodeHistoryMining/lib/org.vcsreader-vcsreader-1.1.0.jar",
		"CodeHistoryMining/lib/annotations-java5-15.0.jar",
		"CodeHistoryMining/lib/commons-csv-1.0.jar",
		"CodeHistoryMining/lib/codehistoryminer-core-1.0.jar",
	].toSet())
}}

def expectToBeEqual(Set actual, Set expected) {
	if (actual != expected) {
		throw new org.gradle.api.GradleException(
			"Expected:\n" +
			expected.join("\n") + "\n" +
			"but was:\n" +
			actual.join("\n")
		)
	}
}

task downloadMavenDependencies() { doLast {
	copyAllMavenDependenciesTo("lib", [configurations.compile])
}}
def copyAllMavenDependenciesTo(String targetDirPath, Collection<Configuration> configurations) {
	ant.delete(dir: targetDirPath)
	for (Configuration configuration : configurations) {
		copyMavenDependenciesTo(targetDirPath, configuration)
	}
}
def copyMavenDependenciesTo(String targetDirPath, Configuration configuration) {
	def files = configuration.files
	def allDependencies = allDependenciesOf(configuration.resolvedConfiguration)

	def dependenciesInfo = allDependencies.collect { ResolvedDependency dependency ->
		def relativePath = (dependency.moduleGroup.split("\\.") + [dependency.moduleName, dependency.moduleVersion]).join(File.separator)
		[path: relativePath, fileName: dependency.moduleName + "-" + dependency.moduleVersion + ".jar"]
	}
	if (!files.collect{it.name}.containsAll(dependenciesInfo.collect{it.fileName})) {
		throw new IllegalStateException(
			"Expected files to contain all dependencies. But was\n" +
			"files:\n${files.join("\n")}\n" +
			"dependencies:\n${dependenciesInfo.join("\n")}"
		)
	}

	dependenciesInfo.each { dependencyInfo ->
		def file = files.find { it.name == dependencyInfo.fileName }
		def dir = new File(targetDirPath + File.separator + dependencyInfo.path)
		dir.mkdirs()
		println("Copying: ${file.canonicalPath}")
		new groovy.util.AntBuilder().copy(
			file: file.canonicalPath,
			todir: dir.canonicalPath
		)
	}
}
def allDependenciesOf(ResolvedConfiguration configuration) {
	configuration.firstLevelModuleDependencies.collectMany { allDependenciesOf(it) }
}
def allDependenciesOf(ResolvedDependency dependency, Set result = []) {
	if (result.containsAll(dependency.children)) [dependency]
	else [dependency] + dependency.children.collectMany{ child -> allDependenciesOf(child) }
}