
# GENERAL -----------------------------------------------------------------

## Transform data to the BNS for calculating times
get_bns <- function(df){
  merged_table %>%
    st_transform(crs = 27700) %>%
    # assign each LSOA to a single, closest, site
    st_join(
      st_transform(df, crs = 27700),
      join = st_nearest_feature
    ) %>%
    # now, summarise our data frame based on site's to find the total population
    group_by(name, org_id) %>%
    # note: summarise will automatically call st_union on the geometries
    # this gives us the lsoa's as a combined multipolygon
    summarise_at(vars("Population", "Activity"), sum) %>%
    st_transform(crs = 4326)
}

## Popups for area and population
get_popup <- function(df){
  glue_data(df,
            "<strong>{name}</strong> ({org_id})",
            "<br/><strong> Estimated Population: </strong>{comma(Population)}",
            "<br/><strong> Theoretical Activity: </strong>{comma(Activity)}",
            ##"<br/><strong> Index of Multiple Deprivation: </strong>{comma(imd)}",
            .sep = "\n")
}

#######################################################################################################################################################

# CURRENT -----------------------------------------------------------------

## Population Chart
get_map_current_population <- function(){
  
  leaflet() %>%
    addProviderTiles(providers$CartoDB.Voyager) %>%
    addPolygons(
      data = merged_table,
      stroke = TRUE,
      color = "black",
      opacity = 0.3,
      weight = 1,
      fillColor = ~pal_fun(Population),
      fillOpacity = 0.5,
      popup = ~as.character(paste0("<strong> County: </strong>", County,
                                   "<br/><strong> LSOA Code: </strong>", `LSOA Code`,
                                   "<br/><strong> LSOA Estimated Population: </strong>", Population,
                                   "<br/><strong> Actual Activity: </strong>", Activity))) %>%
    addCircles(data = current_CL_Site,
               color = "black",
               stroke = TRUE,
               fillColor = "black",
               weight = 5,
               radius = 10,
               opacity = 5,
               fillOpacity = 5) %>%
    addLegend("topleft",
              pal = pal_pop,
              values = lsoa_boundaries_hb$pop,
              title = "LSOA Estimated Population",
              labFormat = labelFormat(),
              opacity = 0.5) %>%
    setView(-4.550000, 52.100000, zoom = 8.5)
}

## Index of Deprivation Density
get_map_current_deprivation <- function(){
  leaflet() %>%
    addProviderTiles(providers$CartoDB.Voyager) %>%
    addPolygons(
      data = merged_table,
      stroke = TRUE,
      color = "black",
      opacity = 0.3,
      weight = 1,
      fillColor = ~pal_fun1(Deprivation_Index),
      fillOpacity = 0.5,
      popup = ~as.character(paste0("<strong> County: </strong>", County,
                                   "<br/><strong> LSOA Code: </strong>", `LSOA Code`,
                                   "<br/><strong> LSOA Estimated Population: </strong>", Population,
                                   "<br/><strong> Total Activity: </strong>", Activity,
                                   "<br/><strong> Deprivation Index: </strong>", Deprivation_Index))) %>%
    addCircles(data = current_CL_Site,
               color = "black",
               stroke = TRUE,
               fillColor = "black",
               weight = 5,
               radius = 10,
               opacity = 5,
               fillOpacity = 5) %>%
    addLegend("topleft",
              pal = pal_index,
              values = merged_table$Deprivation_Index,
              title = "Deprivation Index",
              labFormat = labelFormat(),
              opacity = 0.5) %>%
    setView(-4.550000, 52.100000, zoom = 8.5)
}

## Service Density Chart
get_map_current_service <- function(){
  leaflet() %>%
    addProviderTiles(providers$CartoDB.Voyager) %>%
 
    
    addPolygons(
      data = merged_table1,
      stroke = TRUE,
      color = "grey",
      opacity = 0.3,
      weight = 1,
      fillColor = ~pal_fun2(Activity),
      fillOpacity = 0.5,
      popup = ~as.character(paste0("<strong> County: </strong>", County,
                                   "<br/><strong> LSOA Code: </strong>", `LSOA Code`,
                                   "<br/><strong> LSOA Estimated Population: </strong>", Population,
                                   "<br/><strong> Actual Activity: </strong>", Activity))) %>%
    
    # addPolygons(
    #   data = merged_table,
    #   stroke = TRUE,
    #   color = "black",
    #   opacity = 0.3,
    #   weight = 1) %>%
    
    
    addCircles(data = current_CL_Site,
               color = "black",
               stroke = TRUE,
               fillColor = "black",
               weight = 5,
               radius = 10,
               opacity = 5,
               fillOpacity = 5) %>%
    addLegend("topleft",
              pal = pal_att,
              values = merged_table$Activity,
              title = "LSOA Activity",
              labFormat = labelFormat(),
              opacity = 0.5) %>%
    setView(-4.550000, 52.100000, zoom = 8.5)
}


## LSOA Table - Population & Activity
get_table_current_lsoa <- function(){
  table_temp <-
    as.data.frame(merged_table1) %>%
    rename("Actual Activity" = Activity,
           "Estimated Population" = Population) %>%
    select(-Geometry)
    
  
  table_lsoa <- datatable(
    data = table_temp,
    rownames = FALSE,
    extensions = "Buttons",
    options = list(
      columnDefs = list(list(className = "dt-center", targets = "_all")),
      initComplete = JS(
        "function(settings, json) {",
        "$(this.api().table().header()).css({'background-color': '#04283d', 'color': '#52bfd0'});",
        "}"),
      dom = "Bfrtip",
      buttons = c("copy", "csv", "excel", "pdf", "print"))) %>%
    formatCurrency(columns = 3, currency = "", interval = 3, mark = ",", digits = 0)
  
  return(table_lsoa)
}


## Current Distance Map
get_map_current_distance <- function(polygon, popup, circle){
  leaflet() %>%
    addProviderTiles(providers$CartoDB.Voyager) %>%
    # add the areas that have been assigned to each AS
    addPolygons(
      data = polygon,
      stroke = TRUE,
      color = "black",
      opacity = 0.3,
      weight = 1,
      fillColor = ~pal_fun(Population),
      fillOpacity = 0.5,
      popup = popup) %>%
    # add markers for the AS's
    addCircleMarkers(data = circle,
                     color = "black",
                     stroke = TRUE,
                     fillColor = "white",
                     weight = 1,
                     radius = 3,
                     opacity = 1,
                     fillOpacity = 1) %>%
    setMapWidgetStyle(list(background= "white"))  %>%
    setView(-4.750000, 52.050000, zoom = 8)
  
}

## Current Distance Table
get_table_current_distance <- function(df){
  table_temp <-
    as.data.frame(df) %>%
    select(-Geometry) %>%
    rename("Hospital Site" = name,
           "Hospital Site ID" = org_id,
           "Estimated Population" = Population,
           "Theoretical Activity" = Activity) 
  
  table_temp <- full_join(table_temp, wb_data_table, "Hospital Site")
  
  table_distance <- datatable(
    data = table_temp ,
    rownames = FALSE,
    extensions = "Buttons",
    options = list(
      columnDefs = list(list(className = "dt-center", targets = "_all")),
      initComplete = JS(
        "function(settings, json) {",
        "$(this.api().table().header()).css({'background-color': '#04283d', 'color': '#52bfd0'});",
        "}"),
      dom = "Brttip",
      buttons = c("copy", "csv", "excel", "pdf", "print"))) %>%
    formatCurrency(columns = 3:5, currency = "", interval = 3, mark = ",", digits = 0)
  
  return(table_distance)
}

## Drive Time Mapping
### Combine the data
get_table_current_drive_tmp <- function(df1, df2){
  local({
    x <- table_merge %>%
      st_transform(crs = 27700) %>%
      st_join(df1) %>%
      group_by(LSOA11CD) %>%
      filter(max == min(max)) %>%
      mutate(nx = n() > 1) %>%
      ungroup() %>%
      group_nest(nx)
    
    # splitting this up reduces the amount of computation required: just work out
    # the distance and filter where we have more than 1 match
    x$data[[which(x$nx)]] <- x$data[[which(x$nx)]] %>%
      inner_join(df2 %>%
                   st_transform(crs = 27700) %>%
                   as_tibble() %>%
                   rename(hospital = geometry),
                 by = c("name", "org_id")) %>%
      mutate(dist = map2_dbl(st_centroid(geometry), hospital, st_distance)) %>%
      group_by(LSOA11CD) %>%
      filter(dist == min(dist)) %>%
      select(-dist, -hospital)
    
    # recombine our data
    x <- bind_rows(x$data)
    
    # some lsoa's are missed out in the steps above, add these back in by copying
    # the data from their closest neighbour in x
    y <- table_merge %>%
      st_transform(crs = 27700) %>%
      anti_join(st_drop_geometry(x), by = "LSOA11CD") %>%
      st_join(select(x, -LSOA11CD), join = st_nearest_feature)
    
    # join x and y together
    bind_rows(x, y)
  })
}


### Combine the isochrones
get_table_current_drive_iso <- function(df){
  df %>%
    group_by(name, org_id, max) %>%
    summarise(Observations = sum(Observations)) %>%
    st_transform(4326) %>%
    mutate(time = glue::glue("{max - 10} to {max} mins") %>%
             fct_reorder(max))
}

### Combine and revise catchment areas
get_table_current_drive_points <- function(df1, df2){
  df1 %>%
    inner_join(df2 %>%
                 st_drop_geometry() %>%
                 group_by(name, org_id) %>%
                 summarise(mean_time = sum(center * pop) / sum(pop),
                           across(c(pop, Observations), sum),
                           .groups = "drop"),
               by = c("name", "org_id"))
}


### Build the map
get_map_current_drive <- function(df1_and_column, df1, df2){
  table_temp1 <- levels(df1_and_column)
  table_temp2 <- colorFactor("Blues", table_temp1)
  
  leaflet(df1) %>%
    addProviderTiles(providers$CartoDB.Voyager) %>%
    addPolygons(fillColor = ~table_temp2(time),
                color = "#000000",
                weight = .5,
                fillOpacity = 0.5,
                popup = ~glue::glue("<b>{name}</b>",
                                    "<br><strong> Intervals in Mins: </strong> {time}",
                                    "<br><strong> Theoretical Activity: </strong> {Observations}")) %>%
    
    addMarkers(data = df2,
               popup = ~glue::glue("<b>{name}</b> ({org_id})",
                                   "<br/><strong> Average Time: </strong> {round(mean_time, 0)} m",
                                   "<br/><strong> Estimated Population: </strong> {scales::comma(pop)}",
                                   "<br/><strong> Theoretical Activity: </strong> {scales::comma(Observations)}")) %>%
    addLegend("topleft", 
              pal = table_temp2, 
              values = ~time,
              title = "Drive Time",
              labFormat = labelFormat(),
              opacity = 0.5) %>%
    setView(-4.750000, 52.050000, zoom = 8)
}


## Drive Time Table
get_table_current_drive <- function(df){
  table_temp <-as.data.frame(df) %>%
    rename("Hospital Site" = name,
           "Hospital Site ID" = org_id,
           "Geometry" = geometry,
           "Average Time (mins)" = mean_time,
           "Estimated Population" = pop,
           "Theoretical Activity" = Observations) %>%
    select(-Geometry) %>%
    mutate(`Average Time (mins)` = round(`Average Time (mins)`, 2))
  
  table_temp <- full_join(table_temp, wb_data_table, "Hospital Site")
  
  table_drive <- datatable(
    data = table_temp,
    rownames = FALSE,
    extensions = "Buttons",
    options = list(
      columnDefs = list(list(className = "dt-center", targets = "_all")),
      initComplete = JS("function(settings, json) {",
                        "$(this.api().table().header()).css({'background-color': '#04283d', 'color': '#52bfd0'});",
                        "}"),
      dom = "Brttip",
      buttons = c("copy", "csv", "excel", "pdf", "print"))) %>% 
    formatCurrency(columns = 4:6, currency = "", interval = 3, mark = ",", digits = 0)
  
  return(table_drive)
}


## Drive Time Table Overview 10m
get_table_current_drive_10m <- function(df){
  table_temp <-     as.data.frame(df) %>%
    rename("Hospital Site" = name,
           "Geometry" = geometry,
           "Time Intervals (mins)" = time,
           "Theoretical Activity" = Observations,
           "Hospital Site ID" = org_id,
           "Maximum Drive Time (mins)" = max) %>%
    select(-Geometry)
  
  table_drive <- datatable(
    data = table_temp,
    rownames = FALSE,
    extensions = "Buttons",
    options = list(
      columnDefs = list(list(className = "dt-center", targets = "_all")),
      initComplete = JS(
        "function(settings, json) {",
        "$(this.api().table().header()).css({'background-color': '#04283d', 'color': '#52bfd0'});",
        "}"),
      dom = "Brttip",
      buttons = c("copy", "csv", "excel", "pdf", "print"))) %>%
      formatCurrency(columns = 4, currency = "", interval = 3, mark = ",", digits = 0)
  
  return(table_drive)
}




#######################################################################################################################################################

# PROPOSED ----------------------------------------------------------------

## Distance Map Overview
get_map_distance <- function(polygon, popup, circle){
  map <- leaflet() %>%
    addProviderTiles(providers$CartoDB.Voyager) %>%
    # add the areas that have been assigned to each AS
    addPolygons(
      data = polygon,
      stroke = TRUE,
      color = "black",
      opacity = 0.3,
      weight = 1,
      fillColor = ~pal_fun(Population),
      fillOpacity = 0.5,
      popup =  ~glue::glue("<strong>{name}</strong> ({org_id})",
                           "<br/><strong> Estimated Population: </strong>{comma(Population)}",
                           "<br/><strong> Theoretical Activity: </strong>{comma(Activity)}" ,
                           .sep = "\n")) %>%
    
    
    # add markers for the AS's
    addCircleMarkers(data = circle,
                     color = "black",
                     stroke = TRUE,
                     fillColor = "white",
                     weight = 1,
                     radius = 3,
                     opacity = 1,
                     fillOpacity = 1) %>%
    setMapWidgetStyle(list(background= "white"))  %>%
    setView(-4.750000, 52.050000, zoom = 8)
  
  return(map)
}

## Distance Table Overview
get_table_distance <- function(df){
  table_temp <- as.data.frame(df) %>%
    rename("Hospital Site" = name,
           "Hospital Site ID" = org_id,
           "Estimated Population" = Population,
           "Theoretical Activity" = Activity) %>%
    select(-Geometry)
  
  table_distance <- datatable(
    data = table_temp,
    rownames = FALSE,
    extensions = "Buttons",
    options = list(
      columnDefs = list(list(className = "dt-center", targets = "_all")),
      initComplete = JS(
        "function(settings, json) {",
        "$(this.api().table().header()).css({'background-color': '#04283d', 'color': '#52bfd0'});",
        "}"),
      dom = "Brt",
      buttons = c("copy", "csv", "excel", "pdf", "print"))) %>%
    formatCurrency(columns = 3:4, currency = "", interval = 3, mark = ",", digits = 0)
  
  return(table_distance)
}

## Drive Time Map
### Combine the data
get_table_drive_tmp <- function(df1, df2){
  local({
    x <- table_merge %>%
      st_transform(crs = 27700) %>%
      st_join(df1) %>%
      group_by(LSOA11CD) %>%
      filter(max == min(max)) %>%
      mutate(nx = n() > 1) %>%
      ungroup() %>%
      group_nest(nx)
    
    # splitting this up reduces the amount of computation required: just work out
    # the distance and filter where we have more than 1 match
    x$data[[which(x$nx)]] <- x$data[[which(x$nx)]] %>%
      inner_join(df2 %>%
                   st_transform(crs = 27700) %>%
                   as_tibble() %>%
                   rename(hospital = geometry),
                 by = c("name", "org_id")) %>%
      mutate(dist = map2_dbl(st_centroid(geometry), hospital, st_distance)) %>%
      group_by(LSOA11CD) %>%
      filter(dist == min(dist)) %>%
      select(-dist, -hospital)
    
    # recombine our data
    x <- bind_rows(x$data)
    
    # some lsoa's are missed out in the steps above, add these back in by copying
    # the data from their closest neighbour in x
    y <- table_merge %>%
      st_transform(crs = 27700) %>%
      anti_join(st_drop_geometry(x), by = "LSOA11CD") %>%
      st_join(select(x, -LSOA11CD), join = st_nearest_feature)
    
    # join x and y together
    bind_rows(x, y)
  })
}

### Combine the isochrones
get_table_drive_iso <- function(df){
  df %>%
    group_by(name, org_id, max) %>%
    summarise(Observations = sum(Observations)) %>%
    st_transform(4326) %>%
    mutate(time = glue::glue("{max - 10} to {max} mins") %>%
             fct_reorder(max))
}

### Combine and revise catchment areas
get_table_drive_points <- function(df1, df2){
  df1 %>%
    inner_join(df2 %>%
                 st_drop_geometry() %>%
                 group_by(name, org_id) %>%
                 summarise(mean_time = sum(center * pop) / sum(pop),
                           across(c(pop, Observations), sum),
                           .groups = "drop"),
               by = c("name", "org_id"))
}

### Build the map
get_map_drive <- function(df1_and_column, df1, df2){
  table_temp1 <- levels(df1_and_column)
  table_temp2 <- colorFactor("Blues", table_temp1)
  
  leaflet(df1) %>%
    addProviderTiles(providers$CartoDB.Voyager) %>%
    addPolygons(fillColor = ~table_temp2(time),
                color = "#000000",
                weight = .5,
                fillOpacity = 0.5,
                popup = ~glue::glue("<b>{name}</b>",
                                    "<br><strong>Intervals in Mins: </strong> {time}",
                                    "<br><strong> Theoretical Activity: </strong> {Observations}")) %>%
  
    addMarkers(data = df2,
               popup = ~glue::glue("<b>{name}</b> ({org_id})",
                                   "<strong> Average Time: </strong> {round(mean_time, 0)} m",
                                   "<strong> Estimated Population: </strong> {scales::comma(pop)}",
                                   "<strong> Theoretical Activity: </strong> {scales::comma(Observations)}",
                                   .sep = "<br>")) %>%
    addLegend("topleft", 
              pal = table_temp2, 
              values = ~time,
              title = "Drive Time",
              labFormat = labelFormat(),
              opacity = 0.5) %>%
    setView(-4.750000, 52.050000, zoom = 8)
}

## Drive Time Table 
get_table_drive <- function(df){
  table_temp <- as.data.frame(df) %>%
    rename("Hospital Site" = name,
           "Hospital Site ID" = org_id,
           "Geometry" = geometry,
           "Average Time (mins)" = mean_time,
           "Estimated Population" = pop,
           "Theoretical Activity" = Observations) %>%
    mutate(`Average Time (mins)` = round(`Average Time (mins)`, 2)) %>%
    select(-Geometry)
  
  table_drive <- datatable(
    data = table_temp,
    rownames = FALSE,
    extensions = "Buttons",
    options = list(
      columnDefs = list(list(className = "dt-center", targets = "_all")),
      initComplete = JS(
        "function(settings, json) {",
        "$(this.api().table().header()).css({'background-color': '#04283d', 'color': '#52bfd0'});",
        "}"),
      dom = "Brt",
      buttons = c("copy", "csv", "excel", "pdf", "print"))) %>%
    formatCurrency(columns = 4:5, currency = "", interval = 3, mark = ",", digits = 0)
  
  return(table_drive)
}

## Drive Time Table Overview 10m
get_table_drive_10m <- function(df){
  table_temp <-     as.data.frame(df) %>%
    rename("Hospital Site" = name,
           "Geometry" = geometry,
           "Time Intervals (mins)" = time,
           "Theoretical Activity" = Observations,
           "Hospital Site ID" = org_id,
           "Maximum Drive Time (mins)" = max) %>%
    select(-Geometry)
  
  table_drive <- datatable(
    data = table_temp,
    rownames = FALSE,
    extensions = "Buttons",
    options = list(
      columnDefs = list(list(className = "dt-center", targets = "_all")),
      initComplete = JS(
        "function(settings, json) {",
        "$(this.api().table().header()).css({'background-color': '#04283d', 'color': '#52bfd0'});",
        "}"),
      dom = "Brttip",
      buttons = c("copy", "csv", "excel", "pdf", "print"))) %>%
    formatCurrency(columns = 4, currency = "", interval = 3, mark = ",", digits = 0)
  
  return(table_drive)
}


