region_group_to_factor_ <- function(DT, col="region_group", group_order) {
  if (col %ni% names(DT)) {
    stop ("col '", col, "' is not a name of the DT")
  }

  key.bak <- key(DT)
  on.exit(setkeyIfNot(DT, key.bak, verbose=FALSE))

  if (missing(group_order))
    group_order <- get_region_group_ordering()
  
  levs <- DT[[col]] %>% as.character %>% c(group_order, .) %>% setdiff("ROW") %>% unique %>% c("ROW")

  ## check if any new groups have been added
  if (length(wh.new <- setdiff(levs, group_order))) {
    warning ("There are new region_groups. Make sure to update get_region_group_ordering()\nNew groups: ", pasteQand(wh.new))
  }

  DT[, (col) := factor(as.character(get(col)), levels=levs)]
}



get_region_group_ordering <- function() {
  c(
      'North America'
    , 'Nordics'
    , 'GSA'
    , 'UK+IE'
    , 'France'
    , 'ES+PT'
    , 'GR+IT'
    , 'BeNeLux'
    , 'EE Core'
    , 'EE Core II'
    , 'LatAm Core'
    , 'AU+NZ'
    , 'Turkey'
    , 'Russia'
    , 'CIS ex RU'
    , 'IndiaPakistan'
    , 'Asia Core'
    , 'Africa Core'
    , 'Rest of Europe'
    , 'Rest of LatAm'
    , 'Rest of Asia'
    , 'Rest of Africa'
    , 'ROW'
  )
}



get_store_group_ordering <- function() {
  c(
      'North America'
    , 'Nordics'
    , 'GSA'
    , 'UK+IE'
    , 'France'
    , 'ES+PT'
    , 'GR+IT'
    , 'BeNeLux'
    , 'EE Core'
    , 'EE Core II'
    , 'LatAm Core'
    , 'AU+NZ'
    , 'Turkey'
    , 'Russia'
    , 'CIS ex RU'
    , 'IndiaPakistan'
    , 'Asia Core'
    , 'Africa Core'
    , 'Rest of Europe'
    , 'Rest of LatAm'
    , 'Rest of Asia'
    , 'Rest of Africa'
    , 'ROW'
  )
}



get_store_group_ordering <- function() {
  c(
       'Apple'
    ,  'Spotify'
    ,  'YouTube'
    ,  'Amazon'
    ,  'Google'
    ,  'deezer'
    ,  'Rhapsody'
    ,  'Xbox'
    ,  'eMusic'
    ,  'rDio'
    ,  'Vevo'
    ,  'Muve'
    ,  'MediaNet'
    ,  'Tidal'
    ,  'Verizon'
    ,  'Film Biz Stores'
    ,  'zUncategorized Store'
  )
}
