buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven { url = 'https://files.minecraftforge.net/maven' }
    }
    dependencies {
        classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '3.+', changing: true
    }
}

plugins {
    id "com.matthewprenger.cursegradle" version "1.1.0"
    id 'de.undercouch.download' version '3.3.0'
}
repositories {
    jcenter()
    mavenCentral()
    maven {
        name 'LDTTeam - Modding'
        url 'https://ldtteam.jfrog.io/ldtteam/modding/'
    }
    flatDir {
        dirs 'libs'
    }
}

apply plugin: 'net.minecraftforge.gradle'
apply plugin: 'jacoco'
apply plugin: 'maven-publish'
apply plugin: 'idea'
apply plugin: 'eclipse'
apply plugin: 'maven'

jacocoTestReport {
    reports {
        xml.enabled true
    }
}

sourceSets {
    api {
        java {
            srcDir 'src/api/java'
        }
        compileClasspath += configurations.getByName("minecraft")
    }
    main {
        java {
            srcDir 'src/main/java'
        }
        resources {
            srcDir 'src/main/resources'
            srcDir 'src/main/generated/resources'
        }
        compileClasspath += compileClasspath += sourceSets.api.output
    }
}

ext.configFile = file "build.properties"
configFile.withReader {
    def prop = new Properties()
    prop.load(it)
    ext.config = new ConfigSlurper().parse prop
}

configurations {
    contained {
        transitive = false
    }

    additionalMods {
        transitive = false
    }

    apiImplementation.extendsFrom contained
}

dependencies {
    minecraft "net.minecraftforge:forge:${config.minecraft_version}-${config.forge_version}"

    implementation fg.deobf("com.ldtteam:structurize:${config.structurize_version}")
    contained fg.deobf("com.ldtteam:structurize:${config.structurize_version}")
    additionalMods "com.ldtteam:structurize:${config.structurize_version}"
    compile "com.ldtteam:datagenerators:0.1.38-ALPHA"
    
    implementation fg.deobf("mezz.jei:jei-1.15.2:${config.jei_version}")

    testImplementation  'junit:junit:4.12'
    testImplementation  "org.mockito:mockito-core:1.+"
    testImplementation  group: 'org.powermock', name: 'powermock-module-junit4', version: '1.6.5'
    testImplementation  group: 'org.powermock', name: 'powermock-api-mockito', version: '1.6.5'
    testImplementation  group: 'org.powermock', name: 'powermock-module-junit4-rule-agent', version: '1.6.5'

    testImplementation  'org.assertj:assertj-core:3.9.0'

    testImplementation  group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3'

    implementation 'com.intellij:annotations:+@jar'
    apiImplementation "com.intellij:annotations:+@jar"
}

group = "com.minecolonies"
version = config.minecraft_version.toString() + "-" + System.getenv().containsKey("Version") ? System.getenv("Version") : 'null'
archivesBaseName = "minecolonies"

sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' // Need this here so eclipse task generates correctly.

minecraft {
    // The mappings can be changed at any time, and must be in the following format.
    // snapshot_YYYYMMDD   Snapshot are built nightly.
    // stable_#            Stables are built at the discretion of the MCP team.
    // Use non-default mappings at your own risk. they may not always work.
    // Simply re-run your setup task after changing the mappings to update your workspace.
    mappings channel: 'snapshot', version: "${config.mappings}"
    // makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable.

    accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')

    // Default run configurations.
    // These can be tweaked, removed, or duplicated as needed.
    runs {
        client {
            workingDirectory project.file('runClient')

            // Recommended logging data for a userdev environment
            property 'forge.logging.markers', 'SCAN'

            // Recommended logging level for the console
            property 'forge.logging.console.level', 'info'

            // OPTIFINE GUIDE
            // find and download/compile latest OptiFineDevTweaker, classifier "all"
            // put this and (unpacked) optifine into mods in runClient folder
            // alternate or comment out (if you have default gradle cache location) next property to target "caches/forge_gradle/minecraft_repo/versions/{mcVersion}/client.jar"
            // property 'ofdev.mcjar', 'P:\\apps\\common\\gradle-cache\\caches\\forge_gradle\\minecraft_repo\\versions\\1.15.2\\client.jar'

            mods {
                minecolonies {
                    source sourceSets.main
                    source sourceSets.api
                }
            }
        }

        server {
            workingDirectory project.file('runServer')

            // Recommended logging data for a userdev environment
            //property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'

            // Recommended logging level for the console
            property 'forge.logging.console.level', 'info'

            mods {
                minecolonies {
                    source sourceSets.main
                    source sourceSets.api
                }
            }
        }

        data {
            workingDirectory project.file('runData')

            property 'forge.logging.console.level', 'info'

            args '--mod', 'minecolonies', '--all', '--output', file('src/main/generated/resources'), '--input', file('src/main/resources')

            mods {
                minecolonies {
                    source sourceSets.main
                    source sourceSets.api
                }
            }
        }
    }
}

//From forge
task downloadCrowdin() {
    ext {
        output = file('build/crowdin_raw.zip')
        update = file('build/crowdin.json')
        id = 'minecolonies'
    }
    onlyIf {
        System.getenv().containsKey("crowdinKey") && !project.gradle.startParameter.isOffline()
    }
    doLast {
        download {
            src "https://api.crowdin.com/api/project/${id}/export?key=${System.getenv("crowdinKey")}&json"
            dest update
            overwrite true
        }
        if (!update.text.contains('success')) {
            throw new RuntimeException("Crowdin export failed, see ${update} for more info")
        }
        download {
            src "https://api.crowdin.com/api/project/${id}/download/all.zip?key=${System.getenv("crowdinKey")}"
            dest output
            overwrite true
        }
    }
}

task crowdin(type: Zip) {
    dependsOn downloadCrowdin
    onlyIf {
        !downloadCrowdin.state.skipped
    }
    baseName = project.name
    version = project.version
    classifier = 'crowdin'
    destinationDir = file('build/distributions')
    from(zipTree(downloadCrowdin.output)){
        eachFile {
            if (!it.path.startsWith('assets/')) {
                it.relativePath = new RelativePath(true, it.relativePath.segments.drop(4))
            }
        }
        exclude { it.isDirectory() }
        rename { it.toLowerCase() }
    }
}

task apiJar(type: Jar) {
    from sourceSets.api.output
    classifier 'api'
}

jar {
    from sourceSets.api.output
    from sourceSets.main.output

    // add crowdin locales
    from { !crowdin.state.skipped ? zipTree(crowdin.archivePath) : null}
    dependsOn crowdin

    manifest {
        attributes([
                'Maven-Artifact': "${project.group}:${project.archivesBaseName}:${project.version}:universal",
                'Timestamp': System.currentTimeMillis(),
                "Specification-Title": "minecolonies",
                "Specification-Vendor": "ldtteam",
                "Specification-Version": "1", // We are version 1 of ourselves
                "Implementation-Title": project.name,
                "Implementation-Version": "${project.version}",
                "Implementation-Vendor" :"ldtteam",
                "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
        ])
    }

    classifier = 'universal'
}

javadoc {
    source += sourceSets.api.allSource
}

task packageJavadoc(type: Jar) {
    from javadoc
    classifier = 'javadoc'
}

task sourceJar(type: Jar) {
    classifier = 'sources'
    from sourceSets.main.allJava
    from sourceSets.api.allJava
}

idea {
    module {
        inheritOutputDirs = true
    }
}

task setupDecompWorkspace {
    afterEvaluate {
        println "Setup"
    }
}

task setupCIWorkspace {
    afterEvaluate {
        println "Setup"
    }
}

task buildModsZip(type: Zip) {
    group "build"

    baseName "mods"

    afterEvaluate {
        from(configurations.additionalMods.files) {
            include '*'
        }

        from (tasks.jar.outputs) {
            include '*'
        }
    }
}

tasks.build.dependsOn buildModsZip

afterEvaluate {
    tasks.buildModsZip.dependsOn tasks.reobfJar
}

curseforge {
    if (System.getenv().CURSEAPIKEY != null && System.getenv().CURSERELEASETYPE != null)
    {
        apiKey = System.getenv().CURSEAPIKEY

        project {
            id = '245506'
            addGameVersion '1.15.2'
            changelog = file('build/changelog.md')
            changelogType = 'markdown'
            releaseType = System.getenv().CURSERELEASETYPE

            addArtifact apiJar

            mainArtifact(jar) {
                relations {
                    requiredDependency 'structurize'
                }
            }
        }
    }
    else
    {
        logger.lifecycle("Cannot run the CurseUpload sequence. No API-Key or release type has been provided.")
    }
}

task("createChangelog") {
    group = 'upload'

    doLast {
        def teamCityURL = "https://buildsystem.ldtteam.com/"
        def file = new FileOutputStream("build/changelog.md")
        def out = new BufferedOutputStream(file)
        def changesXML = new XmlSlurper().parse(teamCityURL + "guestAuth/app/rest/changes?locator=build:(id:" + teamcity["teamcity.build.id"] + ")")

        def changes = changesXML.change
        println("createChangelog: Identified " + changes.size() + " changes to be written into the changelog.")

        out << "# Minecolonies Changelog \n"
        out << "## Version: _" + version + "_ \n"

        if (changes.size() > 0) {
            for (int i = 0; i < changes.size(); i++) {
                def changeDetailsURL = teamCityURL + "guestAuth/app/rest/changes/id:" + changes[i].@id.text()
                def changeDetailsXml = new XmlSlurper().parse(changeDetailsURL)
                def changeComment = changeDetailsXml.comment.text().trim()

                out << "* " + changeComment + "\n"
            }
        } else {
            out << "No Changes detected!"
        }

        out.close()
    }
}

reobf {
    jar {}
    apiJar {}
}

publishing {
    if (System.getenv().containsKey("LDTTeamJfrogUsername") && System.getenv().containsKey("LDTTeamJfrogPassword")) {
        project.logger.log(LogLevel.WARN, "Uploading to JFrog enabled.")
        repositories {
            maven {
                name 'LDTTeamJfrog'
                credentials {
                    username System.getenv().get("LDTTeamJfrogUsername")
                    password System.getenv().get("LDTTeamJfrogPassword")
                }
                url 'https://ldtteam.jfrog.io/ldtteam/mods-maven'
            }
        }
    }
    else {
        project.logger.log(LogLevel.WARN, "Uploading to JFrog disabeled.")
    }

    publications {
        maven(MavenPublication) {
            from project.components.java

            artifact packageJavadoc
            artifact sourceJar
            artifact apiJar

            pom {
                url = 'https://github.com/ldtteam/Minecolonies'
                licenses {
                    license {
                        name = 'GNU GENERAL PUBLIC LICENSE Version 3'
                        url = 'https://www.gnu.org/licenses/gpl-3.0.en.html'
                    }
                }
                developers {
                    developer {
                        id = 'OrionDevelopment'
                        name = 'Marc Hermans'
                        email = 'marc.hermans@ldtteam.com'
                    }
                    developer {
                        id = 'Raycoms'
                        name= 'Ray Neiheiser'
                        email = 'ray.neiheiser@ldtteam.com'
                    }
                }
                contributors {
                    contributor {
                        id = 'ldtteam'
                        name = 'Let\'s Develop Together - Team'
                        email = 'info@ldtteam.com'
                    }
                }
                scm {
                    connection = 'scm:git:git://github.com/ldtteam/minecolonies.git'
                    developerConnection = 'scm:git:ssh://github.com/ldtteam/minecolonies.git'
                    url = 'https://github.com/ldtteam/Minecolonies'
                }
            }

            //Replace all deobf dependencies with normal jar references.
            pom.withXml { xmlProvider ->
                NodeList dependencies = asNode().dependencies
                NodeList allDeps = dependencies.'*';

                // Remove forge deps
                allDeps.findAll() { Node el ->
                    el.artifactId.text() == 'forge' && el.groupId.text() == 'net.minecraftforge'
                }.forEach() { Node el ->
                    el.parent().remove(el)
                }
                //remove forgegradle's mapped suffix from versions & set as optional so anyone else doesn't inherit them
                allDeps.findAll() { Node el ->
                    el.version.text().contains('_mapped_')
                }.each { Node el ->
                    NodeList version = el.version
                    version.each {
                        it.setValue(it.text().substring(0, it.text().indexOf('_mapped_')))
                    }
                }
            }
        }
    }
}