#' Extract information of local and weekly estimates from simulation 
#'
#'
#' @param sim An \code{icm} object returned by \link{simulate.seiqhrf}. 
#' @param market.share between 0 and 1, percentage of local hospital beds in the simulated unit (e.g. state)
#' @param icu_percent between 0 and 1, percentage of patients that should go to ICU among the ones that need hospitality
#' @param total_population True population size, needed only if simulation size is smaller than the true population size due to computational cost etc. 
#' 
#' @return 
#' \itemize{
#' \item \code{plot:} A \code{ggplot} object, bar charts of count of patients requiring hospitality and ICU respectively
#' \item \code{result:} A dataframe
#'                     \itemize{
#'                       \item \code{week:}  week number from input \code{sim},
#'                        \item \code{hosp:} the number of patients that require hospitality locally,
#'                        \item \code{icu:} the number of patients that require ICU locally. }
#
#' }
#' 



get_weekly_local <- function(sim, market.share = .4, icu_percent = .1, total_population = NULL){
  
  hosp <- sim$df$h.num
  
  
  if(!is.null(total_population)){
    if(total_population < max(sim$df$s.num)) stop("total Population should be larger than simulated size")
    cat("Scalling w.r.t total population")
    hosp <- hosp*total_population/max(sim$df$s.num)
  } 
  
  if(market.share < 0 || market.share > 1) stop("Market share has to be between 0 and 1")
  if(icu_percent < 0 || icu_percent > 1) stop("ICU percentage has to be between 0 and 1")
  
  hosp[is.na(hosp)] <- 0
  
  hosp_week <- split(hosp, ceiling(seq_along(hosp)/7))
  hosp_sum_week <- unlist(lapply(hosp_week, sum))
  t_sz <- length(hosp_sum_week)
  
  plot_hosp_icu_week <- data.frame(wk = rep(seq_along(hosp_sum_week), 2), 
                                   hosp_icu = c(hosp_sum_week, hosp_sum_week*icu_percent), 
                                   group = rep(c("general hopitality", "icu"), each = t_sz))
  
  
  gg <- ggplot(data=plot_hosp_icu_week, aes(x = wk, y = hosp_icu, fill = group)) +
    geom_bar(stat="identity") +
    labs(y="Counts", x = "Week") + 
    scale_x_continuous(breaks = seq(0,t_sz,5), labels= seq(0,t_sz,5))
  
  res <- data.frame(wk = seq_along(hosp_sum_week), hosp = hosp_sum_week, icu = hosp_sum_week*icu_percent)
  rownames(res) <- c()
                    
  return(list("plot" = gg, "result" = res))
  
}