import org.apache.tools.ant.filters.*
/*
 * Since we use the Eclipse Style layout where sources and resources live in the same
 * folders, we need to make some adjustments to Gradle's defaults.
 */

def isTestProject = name.endsWith('tests') || name.endsWith('tests.java8')
def isPlugin = new File("$projectDir/META-INF/MANIFEST.MF").exists()
def sourceDirs = ['src', 'src-gen', 'emf-gen']

sourceSets {
	configure(isTestProject? test : main) {
		java {
			srcDirs = sourceDirs
			srcDir 'xtend-gen'
			include '**/*.java', '**/*.xtend'
		}
		resources {
			srcDirs = sourceDirs
			exclude '**/*.java', '**/*.xtend'
		}
		if (findProperty('compileXtend') == 'true') {
			xtendOutputDir = 'xtend-gen'
		}
	}
	configure(isTestProject? main : test) {
		java.srcDirs = []
		resources.srcDirs = []
	}
}

jar {
	from ('.') {
		include 'about*.*', 'plugin.xml', 'schema/**', 'model/**', 'plugin.properties'
		exclude 'about.mappings'
	}
	from ('.') {
		include 'about.mappings'
		filter(ReplaceTokens, tokens: ['buildId': getBuildId()])
	}
	if (isTestProject) {
		from sourceSets.test.output
	}
}

/**
 * Computes the build type from the project version.
 * When property 'upstreamBranch' has been set the build type is 'I'.
 *
 * @return I,M,R (Integration, Milestone, Release)
 */
def String getBuildType () {
	if (hasProperty('upstreamBranch')) {
		return 'I'
	}
	
	def versionSplit = version.split('\\.')
	if (version.endsWith('SNAPSHOT'))
		return 'I'
	else if (versionSplit.length == 4)
		return 'M'
	else
		return 'R'
}

/**
 * Computes a build identifier as a combination of the build type
 * (Integration,Milestone/Release) and the build timestamp.
 */
def getBuildId () {
	return getBuildType()+buildTime
}


sourcesJar {
	from ('.') {
		include 'about*.*'
	}
	if (isTestProject) {
		from sourceSets.test.allSource
	}
}

if (isTestProject || name.contains('testlanguage')) {
	tasks.withType(Javadoc) {
		enabled = false
	}
	javadocJar.enabled = false
} else {
	artifacts.archives javadocJar
}

// Configuration of meta data required by the Eclipse IDE
eclipse {
	classpath {
		plusConfigurations += [configurations.optional]
		plusConfigurations += [configurations.mwe2Runtime]
		file.whenMerged {
			entries.each { source ->
				if (source.kind == 'src' && source.path.endsWith('-gen') && !source.path.equals('xtend-gen') ) {
					source.entryAttributes['ignore_optional_problems'] = 'true'
				}
				if (source.kind == 'output') {
					source.path = 'bin/main'
				}
			}
		}
	}
	project {
		natures 'org.eclipse.xtext.ui.shared.xtextNature'
		buildCommands.add(0,new org.gradle.plugins.ide.eclipse.model.BuildCommand('org.eclipse.xtext.ui.shared.xtextBuilder'))
		if (isPlugin) {
			natures 'org.eclipse.pde.PluginNature'
			buildCommands.add(new org.gradle.plugins.ide.eclipse.model.BuildCommand('org.eclipse.pde.ManifestBuilder'))
			buildCommands.add(new org.gradle.plugins.ide.eclipse.model.BuildCommand('org.eclipse.pde.SchemaBuilder'))
		}
	}
}
