#!/usr/bin/env Rscript

require(jsonlite)

process.results.dir <- function(results.dir) {
    result.files <- list.files(results.dir, pattern=".*\\.result$")

    result.file.to.record <- function(result.file.name) {
        json <- fromJSON(paste(results.dir, result.file.name, sep="/"))
        data.frame(defender.payoff=json$payoff$defender, attacker.payoff = json$payoff$attacker,
                   game = strsplit(result.file.name, ".", fixed = TRUE)[[1]][1],
                   method = paste(json$methodInfo$method, json$methodInfo$config),
                   trainingTime = json$trainingTime,
                   gameUuid = json$game$id
                   )
    }

    data <- do.call(rbind, Map(result.file.to.record, result.files))
    data <- data[order(data$method, data$game), ]
    write.csv(data,
              paste(results.dir, "res.csv", sep= "/"), row.names=F)

    agg.data <- aggregate(. ~ method+game+gameUuid, data = data, FUN = mean)
    agg.data.sd <- aggregate(. ~ method+game+gameUuid, data = data, FUN = sd)
    agg.data.max <- aggregate(. ~ method+game+gameUuid, data = data, FUN = max)
    agg.data <- merge(x=agg.data, y=agg.data.sd, by=c("method", "game", "gameUuid"), suffixes = c("", ".sd"))
    agg.data <- merge(x=agg.data, y=agg.data.max, by=c("method", "game", "gameUuid"), suffixes = c("", ".max"))
    write.csv(agg.data,
              paste(results.dir, "mean.csv", sep= "/"), row.names=F)
}

Map(process.results.dir, commandArgs(trailingOnly = TRUE))
