# addQuarter.r

addQuarter_ <- function(DT
  ## OLD: , dateCol=intersect(c("month", "date", "download_activity_date", "activity_month", "activity_date"), names(DT))[[1]]
  ## NEW: 
  , dateCol=getDateColNames(DT)
  , quarter=TRUE
  , quarter_and_year=TRUE
  , nms.quarter="quarter"
  , nms.quarter_and_year="quarter_and_year"
) {

## quarter, quarter_and_year :: flags to indicate whether to add the corresponding column
## nms.* the name of the new columns

  is.char_of_length1(dateCol,              fail=TRUE)
  is.char_of_length1(nms.quarter,          fail=TRUE)
  is.char_of_length1(nms.quarter_and_year, fail=TRUE)

  nms <- copy(names(DT))

  if (!quarter && !quarter_and_year) {
    warning ("Both 'quarter' and 'quarter_and_year' were flagged to FALSE, so nothing is being added.")
    return(DT)
  }


  if (dateCol %ni% nms)
    stop ("the dateCol '", dateCol, "' is not a column of the DT")

  if (quarter && nms.quarter %in% nms)
    stop("'", nms.quarter, "' is already a column in the DT")
  if (quarter_and_year && nms.quarter_and_year %in% nms)
    stop("'", nms.quarter_and_year, "' is already a column in the DT")


  if (quarter) 
    DT[, (nms.quarter) := sprintf("Q%i", quarter(get(dateCol)))]
  if (quarter_and_year)
    DT[, (nms.quarter_and_year) := sprintf("%i-Q%i", year(get(dateCol)), quarter(get(dateCol)))]

  ## have the new columns go next to the dateCol
  ind.d <- which(nms == dateCol)
  new_cols <- c(nms.quarter_and_year, nms.quarter)[c(quarter_and_year, quarter)]
  ordering <- c(head(nms, ind.d), new_cols, tail(nms, -ind.d))
  setcolorderpt(DT, start=ordering)

  return(DT)
}


## Whoops!  I wrote a duplicate function
if (FALSE)
addQuarterCol_ <- function(DT, dateCol=getDateColNames(DT), newCol.nm="quarter_and_year", origin=.origin) {
  is.char_of_length1(dateCol, fail=TRUE)
  is.char_of_length1(newCol.nm, fail=TRUE)

  if (newCol.nm %in% names(DT))
    stop(sprintf("'%s' is already a column in the DT", newCol.nm))

  ## two separate lines of code for faster execution
  if (is.date_or_time(DT[[dateCol]]))
    DT[, (newCol.nm) := get(dateCol) %>% {sprintf("%04i-Q%i", year(.), quarter(.))}]
  else
    DT[, (newCol.nm) := get(dateCol) %>% as.Date(origin=origin) %>% {sprintf("%04i-Q%i", year(.), quarter(.))}]
}
