buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'de.undercouch:gradle-download-task:4.1.2'
        classpath 'org.eclipse.jgit:org.eclipse.jgit:5.7.+'
    }
}

plugins {
    id "jacoco"
    id 'com.github.kt3k.coveralls' version '2.12.0'
    id 'java'
    id 'antlr'
    id 'eclipse'
    id 'idea'
    id 'application'
    id "org.sonarqube" version "4.4.1.3373"
}

import de.undercouch.gradle.tasks.download.Download
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.Constants
import org.eclipse.jgit.lib.ObjectId

import java.util.regex.Matcher
import java.util.regex.Pattern

sonar {
  properties {
    property "sonar.projectKey", "wurstscript_WurstScript"
    property "sonar.organization", "wurstscript-1"
    property "sonar.host.url", "https://sonarcloud.io"
  }
}


mainClassName = "de.peeeq.wurstio.Main"
version = "1.8.1.0"

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(11))
    }
}

jacoco {
    toolVersion = "0.8.5"
}

jacocoTestReport {
    reports {
        xml.required.set(true)
    }

    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it,
                    exclude: ['**/ast/**', '**/jassAst/**', '**/jassIm/**', '**/luaAst/**', '**/antlr/**'])
        }))
    }
}

String genDir = "$projectDir/src-gen"

sourceSets {
    main {
        java {
            srcDir genDir
        }
    }
}

repositories {
    mavenLocal()
    mavenCentral()
    maven { url 'https://jitpack.io' }
}

dependencies {
    implementation 'org.jetbrains:annotations:23.0.0'


    // Antlr parsing library
    antlr "org.antlr:antlr4:4.13.1"

    // tool for generating AST-classes
    compileOnly 'com.github.peterzeller:abstractsyntaxgen:062a7ff178'

    // JUnit for testing
    testImplementation group: 'org.testng', name: 'testng', version: '7.8.0'
    testImplementation group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3'

    // Google guava
    implementation 'com.google.guava:guava:32.1.3-jre'

    // Better functional data structures:
    implementation 'io.vavr:vavr:0.10.4'

    // Support for the vscode language server protocol
    implementation group: 'org.eclipse.lsp4j', name: 'org.eclipse.lsp4j', version: '0.21.1'

    // @Nullable annotations
    implementation group: 'org.eclipse.jdt', name: 'org.eclipse.jdt.annotation', version: '2.1.0'

    // Gson for json parsing
    implementation group: 'com.google.code.gson', name: 'gson', version: '2.10.1'

    // Velocity template engine for generating Html documents from Hotdoc documentation
    implementation group: 'org.apache.velocity', name: 'velocity', version: '1.7'

    // Chardet for guessing the file-encoding of a source-file
    implementation 'com.github.albfernandez:juniversalchardet:2.4.0'

    // Crigges' jmpq
    implementation group: 'com.github.inwc3', name: 'jmpq3', version: '264c54cfc8'

    // Water's wc3 libs
    implementation 'com.github.inwc3:wc3libs:01fb9e23bf'

    // The setup tool for wurst.build handling
    implementation 'com.github.wurstscript:wurstsetup:475cc7fae8'

    implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'
    implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.4.11'

    implementation group: 'org.eclipse.jgit', name: 'org.eclipse.jgit', version: '6.7.0.202309050840-r'
    implementation group: 'org.eclipse.jgit', name: 'org.eclipse.jgit.ssh.apache', version: '6.7.0.202309050840-r'

    // Smallcheck testing library:
    testImplementation group: 'com.github.peterzeller', name: 'java-smallcheck', version: '3f6a178ba7'
}

configurations.all {
    exclude group: "org.slf4j", module: "slf4j-log4j12"
    exclude group: "log4j", module: "log4j"
}

task genAst {
    description = 'Compile ast specifications'
    fileTree(dir: 'parserspec', include: '**/*.parseq').each { file ->
        Pattern PACKAGE_PATTERN = Pattern.compile("package\\s+(\\S+)\\s*;")
        String fileContents = file.text

        Matcher matcher = PACKAGE_PATTERN.matcher(fileContents)
        String packageName = ""
        if (matcher.find()) {
            packageName = matcher.group(1)
        }

        String targetDir = "$genDir/" + packageName.replace(".", "/")

        inputs.file(file)
        outputs.dir(targetDir)

        doLast {
            javaexec {
                classpath configurations.compileClasspath
                main = "asg.Main"
                args = [file, targetDir]
            }
        }
    }
}


task versionInfoFile {
    description "Generates a file CompileTimeInfo.java with version number etc."

    String gitRevision = "unknown-version"
    String gitRevisionlong = "unknown-version"

    Git git = Git.open(new File(rootProject.projectDir, '..'))
    ObjectId head = git.getRepository().resolve(Constants.HEAD)

    gitRevision = head.abbreviate(8).name()
    gitRevisionlong = head.getName()

    String tag = git.describe().setTarget(head).setAlways(true).setTags(true).call()

    String wurstVersion = "${version}-${tag}"
    inputs.property("wurstVersion", wurstVersion)

    def dir = new File('./src-gen/de/peeeq/wurstscript/')
    def f = new File(dir, 'CompileTimeInfo.java')
    outputs.file(f)

    doLast {
        dir.mkdirs()

        String currentTime = new Date().format("yyyy/MM/dd KK:mm:ss")

        f.text = """
        package de.peeeq.wurstscript;

        public class CompileTimeInfo {
            public static final String time="${currentTime}";
            public static final String revision="${gitRevision}";
            public static final String revisionLong="${gitRevisionlong}";
            public static final String version="${wurstVersion}";
        }
        """

    }
}


task gen {
    description "Generates code from various input files"
}
gen.dependsOn genAst
gen.dependsOn versionInfoFile
gen.dependsOn generateGrammarSource

compileJava.dependsOn gen


test {
    // set minimal heap size required to run tests:
    jvmArgs = ['-Xms256m']

    useTestNG() {
        suites 'src/test/resources/AllTestsSuite.xml'
    }
}

// delete the generated sources on clean
clean.doFirst {
    delete genDir
}


apply plugin: 'de.undercouch.download'

task downloadZipFile(type: Download) {
    src 'https://github.com/wurstscript/wurstStdlib2/archive/master.zip'
    dest new File(buildDir, 'stdlib2.zip')
}

task downloadAndUnzipFile(dependsOn: downloadZipFile, type: Copy) {
    from zipTree(downloadZipFile.dest)
    into new File(buildDir, '/deps/')
}

apply from: 'deploy.gradle'