/*
 * Copyright (c) 2023, WSO2 LLC. (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

description = 'Ballerina - EDI tools'

def packageName = "editools"
def packageOrg = "ballerina"
def tomlVersion = stripBallerinaExtensionVersion("${project.version}")
def ballerinaTomlFilePlaceHolder = new File("${project.rootDir}/build-config/resources/Ballerina.toml")
def ballerinaTomlFile = new File("$project.projectDir/Ballerina.toml")

task updateTomlFiles {
    // Update the Ballerina.toml and Dependencies.toml files
    doLast {
        println "Updating toml files"
        def newConfig = ballerinaTomlFilePlaceHolder.text.replace("@project.version@", project.version)
        newConfig = newConfig.replace("@toml.version@", tomlVersion)
        ballerinaTomlFile.text = newConfig
    }
}

task buildEDIToolCore() {
    // Build the ballerina tools
    doLast {
        project.exec {
            ignoreExitValue true
            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                commandLine 'cmd', '/c', "bal build"
            } else {
                commandLine 'sh', '-c', "bal build"
            }
        }
    }
}

task deleteTarget {
    // Delete the target directory
    doLast {
        delete 'target'
    }
}

task copyEdiToolsJar {
    // Copy edi-tools jar to resources folder
    doLast {
        copy {
            from "target/bin/editools.jar"
            into "../edi-tools-cli/src/main/resources"
            include "*.jar"
        }
        println "Copying edi-tools jar to resources folder"
    }
}
task test{
    doLast {
        try {
            // Run tests for each sample
            exec {
                    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                        commandLine 'cmd', "/c", 'bal test --code-coverage --coverage-format=xml'
                    } else {
                        commandLine 'sh', "-c", 'bal test --code-coverage --coverage-format=xml'
                    }
            }
        } catch (Exception e) {
            println("Test Run failed: " + e.message)
            throw e
        }

    }

}

task build {
    dependsOn deleteTarget
    dependsOn updateTomlFiles
    dependsOn buildEDIToolCore
    dependsOn copyEdiToolsJar
    dependsOn test
}

buildEDIToolCore.dependsOn deleteTarget
buildEDIToolCore.dependsOn updateTomlFiles
copyEdiToolsJar.dependsOn buildEDIToolCore
test.dependsOn buildEDIToolCore
