#' packageRankWrapperDriver
#' 
#' @import packageRank
#' @import pkgsearch
#' 
#' @description driver to invoke packageRankWrapper()
#'
#' @param author character string author last name
#' @param date_start character string like "2026-07-05"
#' @param date_end character string like "2026-07-05"
#'
#' @examples
#' \donttest{
#' # takes too long for CRAN test
#' l<-packageRankWrapperDriver(author="Zeeberg",date_start="2026-07-05",date_end="2026-07-06")
#' }
#'
#' @return returns a list whose components are return value of packageRankWrapper()
#'
#' @export
packageRankWrapperDriver<-
	function(author,date_start,date_end) {
		dates <- as.character(seq(as.Date(date_start), as.Date(date_end), by = "day"))
		ld<-length(dates)
		if(ld>5)
		  stop("Please limit the date range to no more than 5 days")
		ll<-list()
		l<-list()
		for(i in 1:ld)
			l[[i]]<-packageRankWrapper(author,dates[i])
		#x_l<-l
		#save(x_l,file="~/saved/x_l.RData")
		ll$summary<-packageRankSummary(l,dates)
		ll$daily<-l
		return(ll)
	}

#' packageRankWrapper
#' @description wrapper to invoke packageRank()
#'
#' @param author character string author last name
#' @param date character string like "2026-07-05"
#'
#' @examples
#' \donttest{
#' # takes too long for CRAN test
#' l<-packageRankWrapper(author="Zeeberg",date="2026-07-05")
#' }
#'
#' @return returns a portion of the returned value of packageRank()
#'
#' @export
packageRankWrapper<-
	function(author,date) {		
		packages <- pkgsearch::advanced_search(Author = author, size = 100)$package
		pr<-packageRank(package=packages,date=date)
		x<-pr[["package.data"]]
		x_sort<-x[rev(order(x$percentile)), ]
		return(x_sort)
	}

#' packageRankSummary
#' @description wrapper to invoke packageRank()
#'
#' @param l return value of packageRankWrapper()
#' @param dates vector of character string like "2026-07-05"
#'
#' @examples
#' l<-packageRankSummary(x_l,dates=c("2026-07-05","2026-07-06"))
#'
#' @return returns a summary of packageRank()
#'
#' @export
packageRankSummary<-
  function(l,dates) {
    ll<-length(l)
    nr<-nrow(l[[1]])
    m<-matrix(0,nrow=nr,ncol=ll)
    colnames(m)<-dates
    rownames(m)<-l[[1]]$package
    for(i in 1:ll) {
      for(r in 1:nr) {
        w<-which(l[[i]]$package==rownames(m)[r])
        if(length(w)==1)
          m[rownames(m)[r],i]<-l[[i]]$percentile[w]
      }
    }
    return(m)
  }


