#!/usr/bin/env Rscript

require(jsonlite)
require(ggplot2)
require(reshape2)

build.stat.table <- function(stat.dir) {
    files <- list.files(path = stat.dir, pattern = "\\.stat$", recursive = TRUE, full.names = TRUE)
    make.row <- function(path) {
        json <- fromJSON(path)
        data.frame(gameUuid=json$gameId, nodes = json$nodes)
    }
    do.call(rbind, Map(make.row, files))
}

read.results.table <- function(file.list) {
    read.results <- function(path) {
        read.csv(path)
    }
    do.call(rbind, Map(read.results, file.list))
}

create.joint.results <- function(stat.dir, file.list) {
    stat.table <- build.stat.table(stat.dir)
    results.table <- read.results.table(file.list)
    merge(stat.table, results.table, by.x=c("gameUuid"), by.y=c("gameUuid"))
}

aggregate.data <- function(output.file, stat.dir, file.list) {
    results <- create.joint.results(stat.dir, file.list)
    results$method=as.character(results$method)
    results$method[results$method==" bosansky-searchgame-config.json"] <- "Bosansky MILP"
    results$method[results$method=="Bosansky MILP "] <- "Bosansky MILP"
    results$method[results$method==" momentum-ir4-deep-max.json"] <-"Mixed Tree momentum-ir4-deep-max.json"
    results$nodes <- 10 ** round(log10(results$nodes))
    wide <- reshape(results, idvar = "gameUuid", timevar = "method", direction = "wide") 
    print(unique(results$method))
    results$method[results$method=="Bosansky MILP"] <- "BC2015"
    results$method[results$method=="Mixed Tree momentum-ir4-deep-max.json"] <- "O2UCT"
    results$method[results$method==" correlated-ai-milp.json"] <- "Cermak 2016"
    results$method <- factor(x = results$method, levels=c("O2UCT", "BC2015", "Cermak 2016"))
    agg <- aggregate(results[,c("trainingTime")], by = list(nodes = results$nodes, method = results$method), FUN=mean)
    write.csv(agg, output.file)
    pdf(paste(output.file,"pdf", sep="."), width=4, height=2.5)
    print(
        ggplot(agg, mapping=aes(x=nodes, y=x, color=method, shape=method, linetype=method))+geom_point()+geom_line()+
        scale_y_log10()+scale_x_log10()+theme_minimal()+
        theme(legend.position = c(0.8, 0.2))+labs(y="Time [s]",x="Game nodes")
    )
    dev.off()
    diffs <- pmax(0, wide$`defender.payoff.Bosansky MILP`-wide$`defender.payoff.Mixed Tree momentum-ir4-deep-max.json`)
    print(length(diffs)-sum(is.na(diffs)))
    pdf(paste(output.file, "hist", "pdf", sep="."))
    print(
        qplot(diffs, geom="histogram")
    )
    dev.off()

    pdf(paste(output.file, "dev", "pdf", sep="."), width=5, height=2.2)
    aggr <- data.frame(diffs = diffs, nodes = wide$`nodes.Bosansky MILP`)
    aggr <- aggr[!is.na(diffs),]
    print(
        ggplot(aggr, mapping=aes(group=nodes, x=nodes, y=diffs))+geom_boxplot()+scale_x_log10()+scale_y_continuous(limits=c(0,0.05))+labs(x="Game nodes", y="O2UCT payoff difference")+theme_minimal()
    )
    dev.off()
}

output.file <- commandArgs(trailingOnly = TRUE)[1]
stat.dir <- commandArgs(trailingOnly = TRUE)[2]
file.list <- commandArgs(trailingOnly = TRUE)[c(-1, -2)]

aggregate.data(output.file, stat.dir, file.list)
