if (release != 'rtm') {
    version += "-$release"
}

if(!npmName)
    npmName = name;

if(!["amd", "cjs"].contains(platform))
    throw new Exception("Invalid platform specified: $platform");

def moduleTypes = [
    "amd": "amd",
    "cjs": "commonjs"
]

ext.packageName="$npmScope/$npmName-$platform";

def srcDir = "$projectDir/src"
def typingsDir = "$srcDir/typings"
def distDir = "$buildDir/dist/$platform"
def testDir = "$buildDir/test/$platform"
def moduleType = moduleTypes[platform]

def sourceSets = ["main", "amd", "cjs", "test"];

task printVersion {
    doLast {
        println "version: $version"
        println "packageName: $packageName"
        println "platform: $platform"
        println "module: $moduleType"
    }
}

task clean {
    doLast {
        delete buildDir
        delete "node_modules/$packageName"
        delete typingsDir
    }
}

task cleanNpm {
    doLast {
        delete 'node_modules'
    }
}

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

sourceSets.each {
    def setName = it.capitalize();

    def destDir = "$buildDir/compile/$it"
    def declDir = "$typingsDir/$it"
    def setDir = "$projectDir/src/$it"

    task "_copyJs$setName"(type:Copy) {
        from "$setDir/js"
        into distDir
    }

    task "_compileTs$setName"(dependsOn: _npmInstall, type:Exec) {
        inputs.dir("$setDir/ts")
        inputs.file("$srcDir/tsconfig.json")
        inputs.file("$setDir/tsconfig.json")
        outputs.dir(destDir)
        outputs.dir(declDir)

        commandLine 'node_modules/.bin/tsc',
            '-p', "$setDir/tsconfig.json",
            '-m', moduleType,
            '--outDir', destDir,
            '--declarationDir', declDir
    }

    task "_buildTs$setName"(dependsOn: "_compileTs$setName", type:Copy) {
        from tasks.getByPath("_compileTs$setName");
        into distDir
    }
}

_compileTsAmd {
    dependsOn _buildTsMain
}

_buildTsTest {
    into testDir
}

_copyJsTest {
    into testDir
}

task _packageMeta(type: Copy) {
    inputs.property("version", version)
    from('.') {
        include '.npmignore', 'readme.md', 'license', 'history.md'
    }
    from("$srcDir/package.template.json") {
        expand project.properties
        rename { "package.json" }
    }
    into distDir
}

task build(dependsOn: [_copyJsMain, _copyJsAmd, _npmInstall, _buildTsMain, _buildTsAmd, _packageMeta]) {

}

_compileTsTest {
    dependsOn build
}

task buildTests(dependsOn: [_copyJsTest, _buildTsTest]) {
}

task test(dependsOn: buildTests, type: Exec) {
    commandLine 'node', "$testDir/run-amd-tests.js"
}

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

    commandLine 'npm', 'pack'
}