import org.jetbrains.kotlin.MPPTools

def exitCodes = [:]

MPPTools.addTimeListener(project)


task konanRun {
    dependsOn "configureBuild"
    (1..project.ext.repeatNumber).each { number ->
        project.ext.buildSteps.keySet().each {
            dependsOn "$it$number"
        }
    }
}

task configureBuild {
    doLast {
        mkdir "${layout.buildDirectory.get().asFile.absolutePath}"
    }
}

(1..project.ext.repeatNumber).each { number ->
    project.ext.buildSteps.each { taskName, command ->
        tasks.create(name: "$taskName$number", type: Exec) {
            commandLine command
            ignoreExitValue true
            doLast {
                exitCodes[name] = execResult.exitValue
            }
        }
    }
}

task clean {
    delete(layout.buildDirectory)
}

task konanJsonReport {
    doLast {
        def nativeCompileTime = MPPTools.getCompileBenchmarkTime(project.ext.applicationName, project.ext.buildSteps.keySet(),
                project.ext.repeatNumber, exitCodes)
        def nativeExecutable = layout.buildDirectory.file("program${MPPTools.getNativeProgramExtension()}").get().asFile.toString()
        def properties = getCommonProperties() + ['type': 'native',
                                                  'compilerVersion': "${konanVersion}".toString(),
                                                  'benchmarks': "[]",
                                                  'compileTime': nativeCompileTime,
                                                  'codeSize': MPPTools.getCodeSizeBenchmark(project.ext.applicationName, nativeExecutable) ]
        def output = MPPTools.createJsonReport(properties)
        layout.buildDirectory.file(nativeJson).get().asFile.write(output)
    }
}
task jvmRun {
    println("JVM run isn't supported")
}

task jvmJsonReport {
    doLast {
        println("JVM run isn't supported")
    }
}

jvmRun.finalizedBy jvmJsonReport
konanRun.finalizedBy konanJsonReport

private def getCommonProperties() {
    return ['cpu': System.getProperty("os.arch"),
            'os': System.getProperty("os.name"), // OperatingSystem.current().getName()
            'jdkVersion': System.getProperty("java.version"), // org.gradle.internal.jvm.Jvm.current().javaVersion
            'jdkVendor': System.getProperty("java.vendor"),
            'kotlinVersion': "${kotlinVersion}".toString()]
}

