
println "version: $version"

def distDir = "$buildDir/dist"
def testDir = "$buildDir/test"

task clean {
    doLast {
        delete buildDir
        delete 'node_modules/@implab'
    }
}

task cleanNpm {
    doLast {
        delete 'node_modules'
    }
}

task _npmInstall() {
    inputs.file("package.json")
    outputs.dir("node_modules")
    doLast {
        exec {
            commandLine 'npm', 'install'
        }
    }
}

task _legacyJs(type:Copy) {
    from 'src/js/'
    into distDir
}

task _buildTs(dependsOn: _npmInstall, type:Exec) {
    inputs.dir('src/ts')
    inputs.file('tsc.json')
    outputs.dir(distDir)

    commandLine 'node_modules/.bin/tsc', '-p', 'tsc.json'
}

task _packageMeta(type: Copy) {
    inputs.property("version", version)
    from('.') {
        include 'package.json', '.npmignore', 'readme.md', 'license', 'history.md'
    }
    into distDir
    doLast {
        exec {
            workingDir distDir
            commandLine 'npm', 'version', version
        }
    }
}

task build(dependsOn: [_npmInstall, _buildTs, _legacyJs, _packageMeta]) {

}

task _localInstall(dependsOn: build, type: Exec) {
    inputs.file("$distDir/package.json")
    outputs.upToDateWhen {
        new File("$projectDir/node_modules/@implab/core").exists()
    }

    commandLine 'npm', 'install', '--no-save', '--force', distDir
}

task copyJsTests(type: Copy) {
    from 'test/js'
    into testDir
}

task buildTests(dependsOn: _localInstall, type: Exec) {
    inputs.dir('test/ts')
    inputs.file('tsc.test.json')
    outputs.dir(testDir)

    commandLine 'node_modules/.bin/tsc', '-p', 'tsc.test.json'
}

task test(dependsOn: [copyJsTests, buildTests], type: Exec) {
    commandLine 'node', 'run-amd-tests.js'
}

task pack(dependsOn: build, type: Exec) {
    workingDir = distDir

    commandLine 'npm', 'pack'
}