library(ggplot2)
library(gridExtra)

source(as.path(srcDir, "20 Create SomLivre Plots.r"))

# ------------------------------  # 


# ------------------------------  # 
# ------------------------------  # 

byCols <- c("download_date", "upc", "artist")
colsUsing <- c("upc", "artist", "units", "download_date", "startDate", "endDate")

DT.agg <- DB.raw[, list(dailyUnits=sum(units), startDate, endDate), by=byCols]


## Ensure dateCols are Dates
dateCols <- getDateColNames(DT.agg)
DT.agg[, c(dateCols) := lapply(.SD, as.Date, origin="1970-01-01", format="%Y-%m-%d"), .SDcols=dateCols]

## Should be just one UPC per artist
invisible(DT.agg[, list(UPC.COUNT=lunique(upc)), by=artist][, if(any(UPC.COUNT>1)) {cat(paste_l(artist[which(UPC.COUNT>1)])); stop("Some artist has UPC COUNT greater than 1")} else cat("All artist/upcs unique  (all good!)\n") ])

# ~~~~~~~~~~~~~~ MI

## Make into TS DT
DT.ts <- DT.agg[, list(time=as.numeric(download_date), value=dailyUnits, group=artist, upc
                     , startDate, endDate)]
DT.ts <- unique(DT.ts, by=names(DT.ts))



## Add Moving Avg
MA <- function(x, order, ...) {
    if (length(x) - trunc(order/2) < 1)
        return(NA_real_)
    return(forecast::ma(x=x, order=order, ...))
}

mkMAnm <- function(x) paste0("MA_", x, "Day")

DT.ts[, value := as.numeric(value)]
DT.ts[, value := txform(x=value, tx="scale.0.1"), by=group]


MA.ints <- c(3,7,14,21,28)  # c(7, 21)
DT.ts[, mkMAnm(MA.ints) := lapply(MA.ints, function(ord) MA(x=value, order=ord)), by=group]

## col ordering for aesthetics
setcolorderpt(DT.ts, c("time", "value", "group", "startDate", "endDate"))


skip <- NULL
MA.cols   <- mkMAnm(c(7, 21))
MA.colors <- c("dark blue", "plum2")
MA.alphas <- c(1, .4)
MA.sizes  <- c(0.35, 1.6)


groupOrder <- DT.ts[, list(D=min(startDate)), by=group][order(D), group]
DT.ts[, group := factor(group, levels=groupOrder)]
setkey(DT.ts, group)

Pl <- DT.ts[, list(Plots=list(createPlot2(.SD, Title="Spotify", nm=group, dots.alpha=0.1, TS.alpha=0.03, dots.on=TRUE, log.y=FALSE
                                      ,MA.col=MA.cols, MA.alpha=MA.alphas, MA.color=MA.colors, MA.size=MA.sizes, MA.skip=skip, short.name=TRUE)))
            , keyby=group]


## PDF PARAMS
pdfFile <- as.path(outDir, "SomLivre.pdf")
cols <- 1
rows <- 3

Pl[, gridPages(Plots, pdfFile, rows=rows, cols=cols, width=14, height=17, noWarnings=TRUE, open=TRUE, main="\nSomLivre")]


