# parsePlaylistFilename.r

parsePlaylistFilename <- function(filename, verbose=FALSE) {
  
  manual_corrections <- get_userids_with_plus_sign_in_name()

  ## FOR NOW, manually fixing plus-signs in the name
  filename.orig <- copy(filename)
  # filename <- gsub("flying\\+lotus", "flying?lotus", filename)
  # filename <- gsub("bausch\\+lombultra", "bausch?lombultra", filename)
  for (nm in names(manual_corrections))
    filename <- gsub(nm, manual_corrections[[nm]], filename, fixed=TRUE)

  strsplit(filename, "\\+") %>% 
    lapply(., function(x) {
      # if (verbose)
      #   cat(pasteC(head(x, 2), C=" - "), "\n")
      sapply(splitOnFirst(x, "_"), function(y) 
          if (length(y) == 2) setNames(nm=y[[1]], y[[2]])
          else {
            y.cot <- capture.output(y)
            warning ("Issue parsing filename for y = ", y.cot, call.=FALSE)
            # if (verbose) Sys.sleep(2.5) else Sys.sleep(1.5)
            setNames(nm=y.cot)
          }
      )}) %>% 
      do.call(rbind, args=.) %>%
      as.data.table ->
      DT.ret

  ## Clean the part x of y
  DT.ret[, totalparts := as.numeric(gsub(".*_of_(\\d+).*", "\\1", part))]
  DT.ret[, part := as.numeric(gsub("(\\d+)_of_.*", "\\1", part))]
  DT.ret[, filename := filename.orig]

  ## PUT THE CORRECTIONS BACK
  manual_corrections <- invDict(manual_corrections)
  for (nm in names(manual_corrections))
    DT.ret[, user :=  gsub(nm, manual_corrections[[nm]], user, fixed=TRUE)]

  setkeyIfNot(DT.ret, "filename", organize=TRUE, verbose=FALSE, warnForColNameInEnv=FALSE)
  return(DT.ret)
}


get_userids_with_plus_sign_in_name <- function() {
  list(
        ## Original       ## temp
        "flying+lotus" = "flying?lotus"
      , "bausch+lombultra" = "bausch?lombultra"
    ) 
}