library(reshape2)
.us()
setScience(proj="NewHire", subl=FALSE, create=TRUE)

f.tracks  = as.path(dataDir, "tracks_delivered_fake", ext="csv")
f.revenue = as.path(dataDir, "revenue_fake", ext="csv")

tracks  <- fread(f.tracks)
revenue <- fread(f.revenue)
revenue <- as.data.table(read.csv(f.revenue, check.names=FALSE))

## Drop the row-wise Total
tracks [, Total := NULL]
revenue[, Total := NULL]

## Drop the column-wise Total and the empty row
tracks  <- tracks[Store %ni% c("", "Grand Total")]
revenue <- revenue[Store %ni% c("", "Grand Total")]

# ## First column is "Store"
# mnts <- names(tracks)[-1L]

## melt the tracks
tracksm <- melt(tracks, id.var="Store", variable.name="Month")
tracksm[, Month := as.Date(paste0(Month, "-01"), format="%b-%y-%d")]
tracksm[, value := currToNumeric(value)]

## melt the revenue
revenuem <- melt(revenue, id.var="Store", variable.name="Month")
revenuem[, Month := as.Date(paste0(Month, "-01"), format="%b-%y-%d")]
revenuem[, value := currToNumeric(value)]

kCols <- c("Store", "Month")
setkeyv(revenuem, kCols)
setkeyv(tracksm,  kCols)

setnames(revenuem, "value", "revenue")
setnames(tracksm,  "value", "tracks")

## Compute CUMSUM of tracks delivered
tracksm[is.na(tracks), tracks := 0L]
tracksm[, totTracks := cumsum(tracks), by=Store]


## Merge Tracks with Rev
DT <- merge(revenuem, tracksm, all=TRUE)


## Melt the DT for graphing & easier scaling
kColsm <- c("Store", "variable", "Month")
DT.m <- setkeyv( melt(DT, id=kCols),  kColsm)

## Drop any Stores which have not reported ANY revenue at all
StoresToDrop <- DT.m[, all(is.na(value)), by=c(kColsm[1:2])] [(V1), unique(Store)]
DT.m <- DT.m[!.(StoresToDrop)]

## Scale and MA
DT.m[, scaledValue     := scaleunif(value), by=c(kColsm[1:2])]
DT.m[, MA3_scaledValue := forecast::ma(scaledValue, 3), by=c(kColsm[1:2])]

{
  inds <- sprintf("Store%02i", 10)
  ggplot(DT.m[.(inds)], aes(x=Month, y=MA3_scaledValue, color=variable, shape=variable)) + 
  # ggplot(DT.m[.(sprintf("Store%02i", 10))], aes_string(y="scaledValue"), aes(x=Month, color=variable, shape=variable)) + 
     geom_line() + geom_point() + facet_grid(Store~.)
}

revenuem[tracksm, tracks := i.value]



as.Date(tolower(mnts), "%b-%y")
as.Date("1jan1960", "%d%b%Y")

x <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
z <- as.Date(x, "%d%b%Y")


""

mnts <- as.data.table(do.call(rbind, t(strsplit(mnts, "-"))))
mnts <- as.Date(mnts[, sprintf("%s-01-%s", V1, V2) ], format="%b-%d-%y")

