## calcPerc_.r
## Calculate the total per store

calcPerc_ <- function(DT, groupingCols, newCol.nm, valueCol, parentGroup=kCols.store, totalCol=NULL) {
##  Calcualtes the percentage of each groupingCol combination out of each parentGroup
##
##  This is the equivalent to looking at each group in parentGroup as a standalone unit, where the sum of its valueCol is 100% 
##   and then calculating the sum of each groupingCols group and taking that as a percentage of the total for the parentGroup
##

  tempColName <- ".tmp_total_col.."

  ## In the unlikely event that this column is in the DT, adverse effects will occur. Do not proceed
  if (".tmp_total_col." %in% names(DT))
    stop ("The column name '", tempColName, "' is a reserved name in this function calcPerc_() \nPlease rename the column in DT before calling this function.")


  ##  If totalCol was not give explicitly, give it a temp name
  if (is.null(totalCol))
    totalCol <- tempColName

  ## totalCol might already be calculated. In which case, not re-calculating will save time and effort
  if (totalCol %ni% names(DT))
    DT [, (totalCol) := sum(get(valueCol)), by=parentGroup]

  ## The percentages will be calculated at this level
  byCols <- c(parentGroup, groupingCols)


  ## Caclulate the total for each group, then divide by the store total, for the percentage of store total
  DT [, (newCol.nm) := sum(get(valueCol)) / get(totalCol), by=byCols] 

  ## For debugging
  browser(expr="calc", text="in calcPerc_ - right before check on sumsToOne()")

  ## Confrim all of the precentages sum to one, by store
  sumsToOne(DT[, unique(get(newCol.nm)), by=byCols], "V1", by=parentGroup, fail=TRUE)

  ## If we added a temp column, delete it
  ## Note that we do NOT drop the column if it was given a name, as the user might want it for future calls to this function
  if (tempColName %in% names(DT))
    DT[, (tempColName) := NULL]

  return(invisible(DT))
}
