
import net.earthcomputer.multiconnect.buildscript.BuildUtils
import net.fabricmc.loom.task.RemapJarTask
import java.util.regex.Pattern

plugins {
	id 'fabric-loom' version '1.0-SNAPSHOT'
	id 'maven-publish'
	id 'signing'
	id 'com.matthewprenger.cursegradle' version '1.4.0'
	id 'com.modrinth.minotaur' version '2.+'
	id 'com.github.breadmoirai.github-release' version '2.2.12'
	id 'io.codearte.nexus-staging' version '0.30.0'
	id 'io.github.juuxel.loom-quiltflower' version '1.7.3'
}

sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17

allprojects {
	archivesBaseName = rootProject.archives_base_name
	version = rootProject.mod_version
	group = rootProject.maven_group
}

def snapshotPattern = Pattern.compile('(\\d\\d)w(\\d\\d)([a-z])')
def prereleasePattern = Pattern.compile('[\\d.]+-(pre|rc)(\\d+)')
def normalizedVersion = project.minecraft_version
def snapshotMatcher = snapshotPattern.matcher(project.minecraft_version)
def prereleaseMatcher = prereleasePattern.matcher(project.minecraft_version)
if (snapshotMatcher.matches()) {
    normalizedVersion = project.target_release + '-alpha.' + snapshotMatcher.group(1) + '.' + (snapshotMatcher.group(2) as Integer) + '.' + snapshotMatcher.group(3)
} else if (prereleaseMatcher.matches()) {
	def type = prereleaseMatcher.group(1)
	if (type == 'pre') {
        normalizedVersion = project.target_release + '-beta.' + prereleaseMatcher.group(2)
    } else if (type == 'rc') {
        normalizedVersion = project.target_release + '-rc.' + prereleaseMatcher.group(2)
    }
}

processResources {
	duplicatesStrategy = DuplicatesStrategy.WARN
	inputs.property "version", project.version
	inputs.property "mcversion", project.supported_versions ?: normalizedVersion

	from(sourceSets.main.resources.srcDirs) {
		include "fabric.mod.json"
		expand "version": project.version,
				"mcversion": project.supported_versions ?: normalizedVersion
	}

	from(sourceSets.main.resources.srcDirs) {
		exclude "fabric.mod.json"
	}
}

// ensure that the encoding is set to UTF-8, no matter what the system default is
// this fixes some edge cases with special characters not displaying correctly
// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html
tasks.withType(JavaCompile) {
	options.encoding = "UTF-8"
	options.release.set(17)
}

// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
// If you remove this task, sources will not be generated.
task sourcesJar(type: Jar, dependsOn: classes) {
	archiveClassifier.set("sources")
	from sourceSets.main.allSource
	project(':translator-api').afterEvaluate {
		from it.sourceSets.main.allSource
	}
}

task javadocJar(type: Jar, dependsOn: classes) {
	archiveClassifier.set("javadoc")

}

task remapSlimJar(type: RemapJarTask, dependsOn: jar) {
	input = jar.archiveFile
	archiveClassifier.set('slim')
	nestedJars.setFrom([])
}


jar {
	from "LICENSE"
	project(':translator-api').afterEvaluate {
		from it.sourceSets.main.output
	}
}

loom {
	accessWidenerPath = file('src/main/resources/multiconnect.accesswidener')
}

quiltflower {
	addToRuntimeClasspath = true
}

subprojects {
	if (name == 'integrationTest') {
		afterEvaluate {
			dependencies {
				implementation project(':')
				implementation project(':api')
			}
		}
	}
}

repositories {
	maven {
		url 'https://repo.viaversion.com/'
	}
	maven {
		url 'https://maven.parchmentmc.org/'
	}
	maven {
		url 'https://jitpack.io/'
	}
	maven {
		url 'https://pkgs.dev.azure.com/djtheredstoner/DevAuth/_packaging/public/maven/v1/'
	}
}

loom {
	runs {
		client {
			vmArgs "-Dmulticonnect.debugKey=true"
		}
	}
}

dependencies {
	//to change the versions see the gradle.properties file
	// compileOnly project(':stubs') // when https://github.com/FabricMC/fabric-loom/pull/747 is merged
	implementation project(':translator-api')

	runtimeOnly project(path: ':via-translator', configuration: "namedElements")
	runtimeOnly project(path: ':via-translator')

	compileOnly 'com.google.code.findbugs:jsr305:3.0.2'

	minecraft "com.mojang:minecraft:${project.minecraft_version}"
	mappings loom.layered {
		officialMojangMappings()
		parchment("org.parchmentmc.data:parchment-${project.parchment_mcversion}:${project.parchment_version}@zip")
	}
	modCompileOnly "com.github.Earthcomputer:fabric-loader:${project.loader_version}"
	modRuntimeOnly "com.github.Earthcomputer:fabric-loader:${project.loader_version}"
	testImplementation "com.github.Earthcomputer:fabric-loader:${project.loader_version}"

	if (true) {
		modCompileOnly(fabricApi.module('fabric-resource-loader-v0', project.fabric_api_version)) {
			transitive = false // to stop it using its own fabric-loader
		}
		modRuntimeOnly(fabricApi.module('fabric-resource-loader-v0', project.fabric_api_version)) {
			transitive = false // to stop it using its own fabric-loader
		}
		include fabricApi.module('fabric-resource-loader-v0', project.fabric_api_version)
	} else {
		modCompileOnly("net.fabricmc.fabric-api:fabric-api:${project.fabric_api_version}") {
			exclude group: 'net.fabricmc', module: 'fabric-loader'
		}
		modRuntimeOnly("net.fabricmc.fabric-api:fabric-api:${project.fabric_api_version}") {
			exclude group: 'net.fabricmc', module: 'fabric-loader'
		}
	}

	if (!project.devauth_version.isBlank()) {
		modRuntimeOnly("me.djtheredstoner:DevAuth-fabric:${project.devauth_version}") {
			exclude group: 'net.fabricmc', module: 'fabric-loader'
		}
	}

	sourceSets.test.compileClasspath += files({sourceSets.main.compileClasspath.toList()})
//	testImplementation 'org.junit.jupiter:junit-jupiter-api:5.5.2'
	testImplementation 'com.github.Earthcomputer.junit5:junit-jupiter-engine:8785ac4d'
	testImplementation 'org.mockito:mockito-all:1.10.19'
}

test {
	useJUnitPlatform()
	systemProperty 'junit.jupiter.extensions.autodetection.enabled', 'true'
	systemProperty 'org.junit.TestClassResolver', 'net.earthcomputer.multiconnect.TestingExtension'
	workingDir 'run'
}

def changes = file('changelog.txt')
changes = changes.exists() ? changes.getText('UTF-8') : ''

// configure the maven publication
publishing {
	repositories(BuildUtils.repositoryHandler(project))

	publications {
		mod(MavenPublication) {
			artifactId 'multiconnect'
			artifact(remapJar) {
				builtBy remapJar
			}
			artifact(sourcesJar) {
				builtBy sourcesJar
			}
			artifact(javadocJar) {
				builtBy javadocJar
			}
			pom BuildUtils.configurePom
			pom.name = 'multiconnect'
			pom.description = 'The full multiconnect mod JAR'
		}
		slim(MavenPublication) {
			artifactId 'multiconnect-slim'
			artifact(remapSlimJar) {
				builtBy remapSlimJar
				classifier = ''
			}
			artifact(sourcesJar) {
				builtBy sourcesJar
				classifier = 'sources'
			}
			artifact(javadocJar) {
				builtBy javadocJar
				classifier = 'javadoc'
			}
			pom BuildUtils.configurePom
			pom.name = 'multiconnect-slim'
			pom.description = 'The multiconnect mod JAR without the API'
		}
	}
}

signing {
	sign publishing.publications.mod
	sign publishing.publications.slim
}

nexusStaging {
	serverUrl = 'https://s01.oss.sonatype.org/service/local/'
	username = project.hasProperty('ossrhUser') ? ossrhUser : 'foo'
	password = project.hasProperty('ossrhPass') ? ossrhPass : 'bar'
}
closeAndReleaseRepository.mustRunAfter publish

curseforge {
	project {
		apiKey = project.hasProperty('curseForgeKey') ? curseForgeKey : 'baz'
		id = '336018'
		changelog = changes
		releaseType = BuildUtils.isBeta(project) ? 'beta' : 'release'
		addGameVersion project.minecraft_version
		addGameVersion 'Fabric'
		mainArtifact remapJar.archiveFile.get().getAsFile()
		afterEvaluate {
			uploadTask.dependsOn remapJar
		}
	}

	options {
		forgeGradleIntegration = false
	}

}

modrinth {
	token = project.hasProperty('modrinthKey') ? modrinthKey : 'foo'
	projectId = 'sfEDKnlo'
	versionName = version
	versionNumber = version
	uploadFile = remapJar
	changelog = changes
	addGameVersion project.minecraft_version
	addLoader 'fabric'
	addLoader 'quilt'
}

githubRelease {
	token(project.hasProperty('githubKey') ? githubKey.toString() : 'derp')
	owner 'Earthcomputer'
	repo 'multiconnect'
	tagName("v$version")
	releaseName("Version $version for Minecraft ${project.minecraft_version}")
	body changes
	prerelease BuildUtils.isBeta(project)
	releaseAssets remapJar.archiveFile.get().getAsFile()
}
tasks.getByName('githubRelease').dependsOn remapJar

task releaseAll {
	group = 'publishing'
	dependsOn publish
	dependsOn closeAndReleaseRepository
	dependsOn tasks.getByName('curseforge')
	dependsOn tasks.getByName('publishModrinth')
	dependsOn tasks.getByName('githubRelease')
	project(':via-translator').afterEvaluate {
		dependsOn it.tasks.getByName('publishModrinth')
	}
}
closeRepository.mustRunAfter publish
