
library(ggplot2)

createPlot <- function(  TS, Title=NULL, yscale=NULL, MA.col=NULL, dots.on=TRUE
                       , MA.alpha=0.4, TS.alpha=1, dots.alpha=.8, log.y=FALSE
                       , y.nm="Value", x.nm="Time"
                       , ylims=NULL, xlims=NULL) {

  force(MA.col)

  # adqust y axis. Ensure correct input, else default to range of value
  if(length(yscale) != 2 & !is.null(yscale))
    warning("yscale should be a vector of two elements. Defaulting to 'range'")
  if(is.null(yscale) || length(yscale) != 2)
    yscale <- range(TS$value) 

  P <- 
    ggplot(TS, aes(x=time, y=value)) + 
      geom_line(alpha=TS.alpha) + 
      ggtitle(Title) + 
      xlab(x.nm) +
      ylab(y.nm)

  ## Add lims if they were passed
  if (length(xlims)==2)
    P <- P + xlim(xlims)
  if (length(ylims)==2)
    P <- P + ylim(ylims)

  if (dots.on)
    P <- P + 
        geom_point(color="black", size=2.5, shape=20, alpha=dots.alpha*0.8) +
        geom_point(color="white", size=2.0, shape=20, alpha=dots.alpha) #+ 

# return
  P <- {
    if (log.y)
      P + scale_y_log10(limits=yscale)
    else
      P + scale_y_continuous(limits=yscale)
  }

  return(P)
}

# title
# xlab
# ylab


createPlot2 <- function(TS, Title="iTunes Campaigns", nm=NULL, TS.alpha=1, dots.alpha=.8, log.y=TRUE, dots.on=TRUE, 
                        MA.col=NULL, MA.alpha=0.4, MA.color=c("blue"), MA.size=1, MA.skip=NULL, short.name=FALSE,
                        x.nm="Date", y.nm="Total Daily Downloads") {

  if(!is.null(nm)) {
    if (short.name)
      Title <- nm
    else 
      Title <- paste0(Title, " Campaign for ", nm, "\n(UPC ",unique(TS[["upc"]]),")", collapse="\n")
  }


  addl.cols <- c("green2",    "red",      "cyan2",      "cyan")
  addl.nms  <- c("startDate", "endDate", "releaseDate", "preReleaseDate")

  # Crop these down to what is actually present in TS
  addl.nms  <- addl.nms[addl.nms %in% names(TS)]
  addl.cols <- addl.cols[seq_along(addl.nms)]

  # names will be preserved
  addl <- unlist(unique(TS[, .SD, .SDcols=addl.nms]))
  
  ## remove NA or duplicated values
  NAs <- is.na(addl)
  addl <- addl[!NAs]
  addl.cols <- addl.cols[!NAs]

  ## Clean names for addl, removing `Date` suffix
  setattr(addl, "names", gsub("Date$", "", names(addl), ignore.case=TRUE))
  setattr(addl, "names", gsub("^start$", "Campgn Start", names(addl), ignore.case=TRUE))
  setattr(addl, "names", gsub("^end$", "Campgn End", names(addl), ignore.case=TRUE))


  ## Adjust Duplicates
  dups <- duplicated(addl)
  for (a in addl[dups]) {
    inds <- which(addl == a)
    a.nm <- paste0(center(rev(names(addl)[inds]),pad=0), collapse=" / \n ")
    names(addl)[[ inds[[1]] ]] <- a.nm
    addl <- addl[ -inds[-1] ] 
    # also drop the corresponding color
    addl.cols <- addl.cols [ -inds[-1] ]
  }


#  TS <- copy(TS)
#  TS[, time := as.numeric(time)]

  ## Caluculate date range for the graph
  xlims <- range(c(addl, TS[["time"]]))

  # Calculate breaks
  bl <- dateBreaks(rng=xlims, addl=addl, remOverlap=FALSE, roundBy="month")

  ## Main Plot Call
  P <- createPlot(TS, Title=Title, TS.alpha=TS.alpha
                    , MA.col=MA.col, MA.alpha=MA.alpha
                    , dots.alpha=dots.alpha, log.y=log.y, dots.on=dots.on
                    , y.nm=y.nm
                    , x.nm=x.nm)

  ## Add lines for specific dates
 # browser(expr=(nm=="Muchachito Bombo Infierno [ES]"))

  P <- P + geom_vline(xintercept=addl , color=addl.cols) + 
            scale_x_continuous(breaks = bl$breaks, labels= bl$labels) + 
#  xlim(xlims) + 
            theme(  title=element_text(hjust=0.5, size=rel(.7))
                 , axis.text.x = element_text(angle=65, vjust=0.85, size=rel(.8)) 
                 , axis.text.y = element_text(angle=18, size=rel(.8))
                 , axis.title  = element_text(hjust=0.5, size=rel(.8))
                 , panel.grid.minor.y = element_blank()
                 , panel.background = element_rect(fill = "lightgray")
                ) + 
            xlab("") 


  # Add the moving average liens
  if (length(MA.col) > length(MA.colors))
    stop("Not enough colors specified in MA.colors") 

  for (i in setdiff(seq_along(MA.col), MA.skip)) {
    ## Some MA cols are all-NA's.  Only attempt to add the line if they are not all NA.
    ##   Adding this to an NA column will cause an error when trying to print the graph
    if (!all(is.na(TS[[ MA.col[[i]] ]] )))
      P <- P + geom_line(aes_string(y=MA.col[[i]]), color=MA.color[[i]], alpha=MA.alpha[[i]], size=MA.size[[i]])    
  }

  return(P)
}

#  
#  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.skip=skip, short.name=TRUE)))
#              , keyby=group]
#  
#  
#  ## PDF PARAMS
#  pdfFile <- as.path(outDir, "Spotify Spain & Italy Campaigns.pdf")
#  cols <- 1
#  rows <- 3
#  
#  Pl[, gridPages(Plots, pdfFile, rows=rows, cols=cols, width=14, height=17, noWarnings=TRUE, open=TRUE, main="\nSpotify Campaigns in Spain & Italy")]
#  
#  

