---
title: "Top Sites"
date: "`r format(Sys.time(), '%d %B, %Y')`"
params:
  results_list: NULL
  report_details: NULL
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = FALSE)
suppressPackageStartupMessages(library(dplyr))
```

```{r print_results, results = "asis"}
# For each result, will want to print
# The name of the center
# The map with sites
# Table for each site with species, ordered by date last seen (most recent first)
for (i in 1:length(params$results_list)) {
  center_info <- params$results_list[[i]]$center_info
  center_results <- params$results_list[[i]]$results
  
  if (is.null(center_results)) {
    # Results NULL indicate no missing species were found, or queries for 
    # recent nearby sightings returned zero results
    cat("# _No sites returned for ", center_info$name[1], "_\n\n")
  } else {
    cat("# ", center_info$name[1], "Top Sites\n")
    cat("\n")
    
    # See how many new species at each site, retaining lat & lng for printing 
    # map had to get creative to get lat & long through (hence no summarize)
    sites <- center_results %>%
      group_by(locName) %>%
      mutate(num_new = n()) %>%
      select(locName, locId, num_new, lat, lng) %>%
      distinct(locName, .keep_all = TRUE) %>%
      arrange(desc(num_new))
    
    # Only print out maps if we are supposed to
    if (report_details[["include_maps"]][i]) {
      suppressMessages(
        sites_map <- lifeR:::MapSites(sites = sites, 
                                      center_lng = center_info$lng, 
                                      center_lat = center_info$lat)
      )
      
      if (!is.null(sites_map)) {
        print(sites_map)
      } else {
        cat("\n_Map is unavailable, likely due to unresponsive map server._")
      }
    }
    # End of maps
    
    # Make new line after map is printed
    cat("\n\n")

    for (s in 1:nrow(sites)) {
      site_name <- sites$locName[s]
      site_id <- sites$locId[s]
      site_new <- sites$num_new[s]
      site_lat <- sites$lat[s]
      site_lng <- sites$lng[s]
      
      # Pull out only columns of interest, renaming as appropriate
      site_results <- center_results %>%
        filter(locName == site_name) %>%
        select(comName, howMany, obsDt, subId) %>%
        mutate(`Last Seen` = as.Date(obsDt)) %>%
        select(-obsDt) %>%
        rename(Species = comName,
               Count = howMany) %>%
        arrange(desc(`Last Seen`)) %>%
        # Update date shown in Last Seen to be linked to corresponding checklist
        mutate(`Last Seen` = paste0("[", `Last Seen`, "](https://ebird.org/checklist/", subId, ")")) %>%
        select(-subId)
      

      # Create the Google Map URL from coordinates
      google_maps_url <- paste0("https://maps.google.com/maps?q=",
                                site_lat, ",", site_lng)

      # Create the eBird URL from locId (need to test for non-hotspot 
      # localities?)
      eBird_url <- paste0("https://ebird.org/hotspot/",
                          site_id)
      
      # Print info for site      
      cat("## ", s, ". ", site_name, "\n\n", sep = "")
      cat("###", site_new, "species\n\n")
      # Only print hotspot link if it's actually a hotspot
      if(nchar(site_id) > 0) {
        cat("eBird hotspot: [", eBird_url, "](", eBird_url, ")\n\n", sep = "")
      }
      cat("Site on Google Maps: [", site_lat, ", ", site_lng, "](",
          google_maps_url, ")\n\n", sep = "")
      print(knitr::kable(x = site_results))
      cat("\n\n")    
      
    } # end iteration over all sites for this center
    
  } # end conditional for non-null results for this center
  
  # Add horizontal line after each center
  cat("\n***\n")
  
} # end iteration over each element of results_list (i.e. each center)
```

## Report details

Settings for this report:

```{r extract_details, include = FALSE}
  max_sites <- report_details[["max_sites"]]
  dist <- report_details[["dist"]]
  back <- report_details[["back"]]
  hotspot_restrict <- ifelse(test = report_details[["hotspot"]], 
                             yes = "", 
                             no = "**not** ")
  provisional <- ifelse(test = report_details[["include_provisional"]],
                        yes = "", 
                        no = "**do not** ")
  drop_patterns <- report_details[["drop_patterns"]]
```

+ Maximum number of sites to report: `r max_sites`
+ Distance from each center point: `r dist` km
+ Days covered: `r Sys.Date() - back` through `r Sys.Date()`
+ Results `r hotspot_restrict` restricted to hotspots
+ Results `r provisional` include provisional observations
+ Species with the following patterns in their names were excluded: `r paste0(drop_patterns, collapse = ", ")`
