## lookerToBarChart.r

lookerToBarChart <- function(f.in, ratioCol, valueCol, rowsToExclude, MainTitle, hierarchies, TopN=6L, DT.raw=NULL, verbose=verbose) {
## Returns a list of two items:  DT.raw and Plots
## if DT.raw is specified, will use that instead of f.in

  lib(ggplot2)
  lib(scales)


  ## Check which of these two vars is missing
  missing.f.in <- missing(f.in) || is.null(f.in)
  missing.DT   <- missing(DT.raw) || is.null(DT.raw)

  ## Ensure not both missing
  if (missing.f.in && missing.DT) {
    stop("Either f.in or DT.raw must be specified")
  }

  ## Create the f.out based on f.in or the name of the DT
  if (!missing.f.in)
    f.outname <- gsub("\\.(csv|tsv|txt|xls|xlsx)$", "", basename(f.in))
  else 
    f.outname <- pasteC(substitute(DT.raw))

  ## read in the raw data
  if (missing.DT)
    DT.raw <- fread(f.in)


  ## Remove NA's
  nas <- which(is.na(DT.raw), arr.ind=TRUE)
  if (nrow(nas))
    invisible(apply(nas, 1, function(rc) DT.raw[rc[[1]], names(DT.raw)[rc[[2]]] := 0L ] ))

  ## Clean up the column names
  fixLookerColNames_ (DT.raw)

  ### DROP CERTAIN VALUES
  for (col in names(rowsToExclude)) {
    if (col %in% names(DT.raw))
      DT.raw <- DT.raw[!get(col) %in% rowsToExclude[[col]] ]
  }


  ### CLEAN UP SPECIFIC COLUMNS ###
  ### ------------------------- ###
  if ("Audio_or_Video" %in% names(DT.raw)) {
    DT.raw[Audio_or_Video=="", Audio_or_Video := "Other"]
    DT.raw[, Audio_or_Video := setFactorOrder(Audio_or_Video, c("Audio", "Video"), last=c("Other"), showWarnings=FALSE )]
    invisible()
  }

  if ("Continent" %in% names(DT.raw)) {
    DT.raw[Continent=="North America", Continent := "N.America"]
    DT.raw[, Continent := setFactorOrder(Continent, c("N.America", "Europe"), last="ROW")]
    invisible()
  }

  if ("Genre" %in% names(DT.raw)) {
    GenreOrder <- DT.raw[, sum(get(valueCol)), by=Genre][order(V1, decreasing=FALSE), Genre]
    DT.raw[, Genre := setFactorOrder(Genre, GenreOrder)]
  }

  if ("Country" %in% names(DT.raw)) 
    columnTopN_ (DT.raw, col="Country",     valueCol=valueCol, byCols=c("Continent_Group", "Continent"), FUN="sum")
  if ("Label" %in% names(DT.raw)) 
    columnTopN_ (DT.raw, col="Label",       valueCol=valueCol, byCols=c("Continent_Group", "Continent"), FUN="sum")
  if ("Label_Owner" %in% names(DT.raw)) 
    columnTopN_ (DT.raw, col="Label_Owner", valueCol=valueCol, byCols=c("Continent_Group", "Continent"), FUN="sum", TopN=TopN+1)
  ### ------------------------- ###

  
  
  ## PLOT
  Plots <- plotBarChartWithRatios(DT.raw, ratioCol=ratioCol, valueCol=valueCol, f.name=f.outname, timeStamp=TRUE, exclude="Measurement", 
                                  main=MainTitle, sub=orchardFootNote(), hierarchies=hierarchies, height.per.plot=6, width.per.plot=8, verbose=verbose)
  ## Show the f.out file
  verboseMsg(verbose, "fileSaved to:  \t'", attr(Plots, "f.out"), "'", sep="", time=FALSE)

  return(invisible(list(DT.raw=DT.raw, Plots=Plots)))

}