options(warn=-1)
require(jsonlite)
require(ggplot2)

args = commandArgs(trailingOnly=TRUE)

convert2filename<- function(string, ext=".png"){
  string<- gsub("\\[%\\]", "percentage", string)
  string<- gsub("\\[#\\]", "number", string)
  string<- gsub(" ", "_", string)
  return(paste(string, ext, sep=""))
}

summary_json<- jsonlite::fromJSON(args[1])$summary
tablenames<- names(summary_json)[!names(summary_json) %in% c("images", "Trim Parameter")]

summary_json<- summary_json[tablenames]
#summary<- as.data.frame(read.csv(args[1]))
for( i in tablenames[2:length(tablenames)]){

ggplot(summary_json, aes(x=summary_json[,"setname"], y = summary_json[,i]), environment = environment()) +
  geom_bar(stat = "identity",   fill="#67a9cf") +
  theme(axis.text.x=element_text(angle=90, hjust=1, vjust = 0.5), legend.position = "none") +
  ggtitle(i) +
  xlab("Sample")+
  ylab(i)
  ggsave(paste(args[2], convert2filename(i), sep="/"))

}
temp_json <- data.frame(rbind(cbind( setname = summary_json$setname, type = "Total reads [#]", value= summary_json$`Total reads [#]`),
                              cbind( setname = summary_json$setname, type = "Reads after trimming [#]", value= summary_json$`Reads after trimming [#]`)
                   ))
temp_json$value <- as.numeric(as.character(temp_json$value))

ggplot(temp_json, aes(x= ))

ggplot(temp_json, aes(x=setname, y = value, by=type, fill=type))+
  geom_bar(stat="identity",position = "identity", alpha=  0.9) +
  theme(axis.text.x=element_text(angle=90, hjust=1, vjust = 0.5)) +
  ggtitle("Number of Reads") +
  xlab("Sample")+
  ylab("Number of Reads")
ggsave(paste(args[2], "number_of_reads.png", sep="/"))


