library(data.table)

## inaczej zawołac skrypt plots: tak, żeby nazwa zgrupowanych dancyh była
## związana nie tlyko z nazwą configu, ale i z długością rozgrywki.
## (to chyba był głupi pomysł, żeby to tu zaszyć. W wersji 12 trzeba
## rozważyć zmiany. 

results.location <- "/home/jan/research/security_games/gtopt11/"

get.result.for.games <- function(games, config) {
    get.result.for.game <- function(game) {
        file <-  paste0(results.location, "eval-",game,"-*ex40-10-ET-",config,".1.out")
        l <- readLines(pipe(paste0("grep 'The payoff:' ",file,"|tail -n 1| cut -f 2 -d\\: ")))
        data.frame(game=game, result=as.numeric(l))
    }


    
    rbindlist(Map(get.result.for.game, games))
}

get.uniform.result.for.games <- function(games) {
    get.result.for.games(games, "random")
}

get.optimal.result.for.games <- function(games) {
    get.result.for.games(games, "milp")
}



generate.ranking.for.files <- function(files) {
    stat.list <- Map(function (file) cbind(read.csv(file, header = TRUE), file=file), files)
    stat.frame <- rbindlist(stat.list)

    avg.stats <- data.table(game = gsub("-(bp|full|slice)(\\.avg)?\\.csv", "", stat.frame$file), method = gsub("^eval-.*(ex[0-9]*-[0-9]*-(ET|FT))-((full|slice|bp)).*45000-","\\1-\\3-",stat.frame$config), iterations=stat.frame$iterations, result=stat.frame$result)

    games <- unique(avg.stats$game)

    milp.results <- get.optimal.result.for.games(games)
    random.results <- get.uniform.result.for.games(games)

    avg.stats <- merge(avg.stats, milp.results, by="game", suffixes= c("", ".milp"))
    avg.stats <- merge(avg.stats, random.results, by="game", suffixes = c("",".random"))

    avg.stats$score <- (avg.stats$result - avg.stats$result.random)/(avg.stats$result.milp-avg.stats$result.random)
    
    print(head(avg.stats))
    
    best.method.for.game <- avg.stats[,list(best.result=.SD$method[which.max(.SD$result)], best.time=.SD$method[which.min(.SD$iterations)]), by=list(game)]

    print(head(best.method.for.game))
    
    write.csv(best.method.for.game, "best.method.for.game.csv", row.names=FALSE)

    method.ranking <- best.method.for.game[,list(score=.N), by=list(best.result)]
    write.csv(method.ranking[order(method.ranking$score, decreasing = TRUE),], "best.method.ranking.csv", row.names=FALSE)

    high.score.methods <- avg.stats[,list(score=sum(score>=0.95)), by=list(method)]
    write.csv(high.score.methods[order(high.score.methods$score, decreasing=TRUE),], "high.score.methods.csv", row.names=FALSE)
    
}


generate.ranking.for.files(commandArgs(trailingOnly = TRUE))
