#' Forecasting plot.
#' 
#' @aliases do_plot_forec_players
#'
#' @description 
#' Plot with the past and future performance for a certain player, 
#' including forecasting intervals represented with dashed lines.
#' 
#' @usage 
#' do_plot_forec_players(player, b, q, xlabel, ylabel, rm_leg = FALSE, use_plotly = TRUE)
#' 
#' @param player Player's name.
#' @param b Matrix b from \code{\link{b_w}} (past values).
#' @param q Matrix from \code{\link{forec_intervals_ropes}} (predictions).
#' @param xlabel Label for the x-axis.
#' @param ylabel Label for the y-axis.
#' @param rm_leg Logical value to show the legend.
#' @param use_plotly Logical value to get the plot with \code{plotly}. 
#' 
#' @return 
#' Graphical device.
#' 
#' @author 
#' Guillermo Vinue
#'
#' @examples 
#' # See the code.
#' 
#' @importFrom ggplot2 ggtitle
#' @importFrom plotly plotly_build
#' 
#' @export

do_plot_forec_players <- function(player, b, q, xlabel, ylabel, rm_leg = FALSE, use_plotly = TRUE){
  # @param ylimits Limits for the y-axis.
  # @param ybreaks Breaks for the y-axis.
  
  sel_pl <- which(rownames(b) == player)
  # Latest non NA value:
  last_nonNA <- max(which(!is.na(b[sel_pl,])))

  pl <- b[sel_pl,]
  pl_noNA <- pl[!is.na(pl)]
  #pl_estim_future <- result$Z[sel_pl,][(last_nonNA + 1) : dim(result$Z)[2]]
  mid <- (dim(q)[1] + 1)/2
  pl_estim_future_1qu <- q[1, sel_pl, ][(last_nonNA + 1):dim(b)[2]]
  pl_estim_future_3qu <- q[mid, sel_pl, ][(last_nonNA + 1):dim(b)[2]]
  pl_estim_future_5qu <- q[5, sel_pl, ][(last_nonNA + 1):dim(b)[2]]

  ages <- c(names(pl_noNA), names(pl_estim_future_3qu))
  values <- c(as.vector(pl_noNA), as.vector(pl_estim_future_3qu))
  categ <- c(rep("Past values", length(pl_noNA)), 
             rep("Predictions", length(pl_estim_future_3qu)))

  ages1 <- names(pl_estim_future_1qu)
  values1 <- as.vector(pl_estim_future_1qu)
  values2 <- as.vector(pl_estim_future_5qu)

  df1 <- data.frame(Age = ages, GmSc = values, Type = categ) 
  df2 <- data.frame(Age = ages1, GmSc = values1) 
  df3 <- data.frame(Age = ages1, GmSc = values2) 

  player1 <- strsplit(player, "_")[[1]][1]
  
  p <- ggplot() + 
    #geom_line(stat = "identity") +
    #group = 1 if there is only one player.
    geom_line(data = df1, aes(Age, GmSc, colour = Type, group = 1)) +
    #http://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette
    #library(scales) ; show_col(hue_pal()(4)) ; hue_pal()(4)
    geom_line(data = df2, aes(Age, GmSc, group = 1), colour = "#00BFC4", linetype = 2) +
    geom_line(data = df3, aes(Age, GmSc, group = 1), colour = "#00BFC4", linetype = 2) +
    #scale_y_continuous(limits = ylimits, breaks = ybreaks) +   
    ggtitle(player1) + 
    xlab(xlabel) +
    ylab(ylabel) +
    theme(legend.title = element_blank(), # To remove legend name.
          legend.text = element_text(size = 20), 
          legend.key.height = unit(3, "lines"), # To space legend items.
          legend.key.width = unit(3, "lines"), # To space legend items.
          axis.text.x = element_text(angle = 90, size = 12, margin = margin(0,0,25,0), vjust = 0.1),
          axis.text.y = element_text(size = 17, margin = margin(0,0,0,25), vjust = -0.1),
          # vjust and margin allows us to space ticks from the axis
          #axis.ticks.length = unit(0.5, "cm"), # To increase the tick marks.
          axis.title.x = element_text(size = 20),
          axis.title.y = element_text(size = 20),
          plot.title = element_text(size = 20)) 

  if (!rm_leg) {
    p <- p + theme(legend.position = "none")
  }
  
  if (use_plotly) {
    p1 <- plotly_build(p)
    
    # This is to custom the tooltip information when hovering:
    p1$x$data[[1]]$text <- gsub("<br>1: 1", "", p1$x$data[[1]]$text)
    p1$x$data[[2]]$text <- gsub("<br>1: 1", "<br>Median value (CI)", p1$x$data[[2]]$text)
    p1$x$data[[3]]$text <- gsub("<br>1: 1", "<br>Type: Predictions<br>Lower Limit (CI)", p1$x$data[[3]]$text)
    p1$x$data[[4]]$text <- gsub("<br>1: 1", "<br>Type: Predictions<br>Upper Limit (CI)", p1$x$data[[4]]$text)
    # This is needed to join the last value of the line of past values with the first value of the line of predictions.
    p1$x$data[[1]]$x[length(p1$x$data[[1]]$x) + 1] <- p1$x$data[[2]]$x[1]
    p1$x$data[[1]]$y[length(p1$x$data[[1]]$y) + 1] <- p1$x$data[[2]]$y[1]
    ## Margin between the axis title and axis ticks:
    p1$layout$margin[c(3,4)] <- c(100,80)
    
    return(p1) 
  }else{
    return(p)
  }
}  