/*
 * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

import org.apache.tools.ant.taskdefs.condition.Os

apply plugin: 'java'

description = 'Ballerina - Transactions Negative Tests'

configurations {
    jbalTools
    externalJars
}

dependencies {
    compileOnly group: 'org.ballerinalang', name: 'ballerina-runtime', version: "${ballerinaLangVersion}"
    jbalTools ("org.ballerinalang:jballerina-tools:${ballerinaLangVersion}") {
        transitive = false
    }
    externalJars (group: 'io.ballerina.stdlib', name: 'io-native', version: "${stdlibIoVersion}") {
        transitive = false
    }
    compileOnly project(':transaction-native')
    compileOnly project(':transaction-test-utils')
}

clean {
    delete "$project.projectDir/target"
    delete "$project.projectDir/Ballerina.lock"
}

jar {
    manifest {
        attributes('Implementation-Title': project.name,
                'Implementation-Version': project.version)
    }
}

task copyToLib(type: Copy) {
    into "$project.projectDir/lib"
    from configurations.externalJars
}

def tomlVersion = stripBallerinaExtensionVersion("${project.version}")
def ballerinaTomlPlaceHolder = new File("${project.rootDir}/build-config/resources/TransactionNegativeBallerina.toml")
def ballerinaTomlFile = new File("${project.rootDir}/transaction-negative-tests/Ballerina.toml")
def configTomlFile = new File("$project.projectDir/tests/Config.toml")
def originalConfigFileText = configTomlFile.text
def graalvmFlag = ""
def testParams = "--code-coverage --includes=ballerinai.*:org.ballerinalang.stdlib.transaction.*"

task initializeVariables {
    if (project.hasProperty('balGraalVMTest')) {
        graalvmFlag = "--graalvm"
        testParams = "--includes=ballerinai.*:org.ballerinalang.stdlib.transaction.*"
    }
}

def stripBallerinaExtensionVersion(String extVersion) {
    if (extVersion.matches(project.ext.timestampedVersionRegex)) {
        def splitVersion = extVersion.split('-');
        if (splitVersion.length > 3) {
            def strippedValues = splitVersion[0..-4]
            return strippedValues.join('-')
        } else {
            return extVersion
        }
    } else {
        return extVersion.replace("${project.ext.snapshotVersion}", "")
    }
}

task updateTomlVersions {
    doLast {
        def newConfig = ballerinaTomlPlaceHolder.text.replace("@project.version@", project.version)
        newConfig = newConfig.replace("@toml.version@", tomlVersion)
        newConfig = newConfig.replace("@stdlib.io.version@", stdlibIoVersion)
        ballerinaTomlFile.text = newConfig
    }
}

task revertTomlFile {
    doLast {
        configTomlFile.text = originalConfigFileText
    }
}

def setExecPath(configTomlFile, originalConfigFileText, distributionBinPath) {
    def newConfig = originalConfigFileText.replace("@exec.path@", distributionBinPath)
    configTomlFile.text = newConfig
}

task ballerinaNegativeTests {
    inputs.dir file(project.projectDir)
    dependsOn(copyToLib)
    dependsOn(initializeVariables)
    dependsOn(":transaction-ballerina:build")
    dependsOn(":transaction-test-utils:build")
    dependsOn(":transaction-negative-tests:compileJava")
    dependsOn(":transaction-negative-tests:compileTestJava")
    dependsOn(":transaction-negative-tests:jar")
    dependsOn(":transaction-negative-tests:processResources")
    dependsOn(":transaction-negative-tests:processTestResources")
    dependsOn(updateTomlVersions)
    finalizedBy(revertTomlFile)
    doLast {
        def distributionBinPath =  "$project.rootDir/target/ballerina-runtime/bin"
        
        setExecPath(configTomlFile, originalConfigFileText, distributionBinPath)
        exec {
            workingDir project.projectDir
            environment "JAVA_OPTS", "-DBALLERINA_DEV_COMPILE_BALLERINA_ORG=true"
            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                commandLine 'cmd', '/c', "$distributionBinPath/bal.bat test ${graalvmFlag} ${testParams}"
                commandLine 'cmd', '/c', "git diff --quiet -- Ballerina.toml Dependencies.toml || git commit -m \"[Automated] Update the native jar versions\" Ballerina.toml Dependencies.toml"
            } else {
                commandLine 'sh', '-c', "$distributionBinPath/bal test ${graalvmFlag} ${testParams}"
                commandLine 'sh', '-c', "git diff --quiet -- Ballerina.toml Dependencies.toml || git commit -m '[Automated] Update the native jar versions' Ballerina.toml Dependencies.toml"
            }
        }
    }
}

test {
    dependsOn(ballerinaNegativeTests)
}

ballerinaNegativeTests.dependsOn ":transaction-ballerina:build"
ballerinaNegativeTests.dependsOn updateTomlVersions
build.dependsOn test
build.dependsOn updateTomlVersions
