/*
 * Copyright (c) 2021, 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 from: "$rootDir/gradle/jsProject.gradle"

configurations {
    stvisualizer
}

task stVisualizerBuild {
    dependsOn 'updateVersion'
    dependsOn 'updateLernaVersion'
    PatternSet patternSet = new PatternSet();
	patternSet.exclude("**/node_modules/**");
    patternSet.exclude("**/packages/**/build/**");
    patternSet.exclude("**/packages/**/lib/**");
    patternSet.exclude("**/packages/**/coverage/**");

    FileTree src = files('.').asFileTree;
    inputs.files(src.matching(patternSet))

    outputs.dir("packages/distribution/build")
    outputs.cacheIf { true }
    doFirst {
        exec {
            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                commandLine 'cmd', '/c', 'npm', 'run', 'build'
            } else {
                commandLine 'npm', 'run', 'build'
            }
        }
        copy {
            from './packages/distribution/build'
            into './../resources/jslibs'
            include 'stvisualizer.js'
            include 'themes/**'
        }
    }
}

task updateLernaVersion(type: Exec) {
    inputs.file("package.json")

    PatternSet patternSet = new PatternSet()
    patternSet.include("lerna.json")
    patternSet.include("packages/**/package.json")
    FileTree src = files('.').asFileTree
    outputs.files(src.matching(patternSet))

    doFirst {
        println "update lerna version to " + project.version + " in " + project.path
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            commandLine 'cmd', '/c', 'npx', 'lerna', 'version', project.version, '--yes', '--no-git-tag-version', '--no-push'
        } else {
            commandLine 'npx', 'lerna', 'version', project.version, '--yes', '--no-git-tag-version', '--no-push'
        }
    }
}

task testSTVisualizer() {
    onlyIf {
        !assemble.state.upToDate
    }
    doFirst {
        exec {
            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                commandLine 'cmd', '/c', 'npm', 'run', 'test'
            } else {
                commandLine 'npm', 'run', 'test'
            }
        }
    }
}

artifacts.add('stvisualizer', file("packages/distribution/build/"))

check {
    dependsOn testSTVisualizer
}
