library(tidyverse)
## Loading tidyverse: ggplot2
## Loading tidyverse: tibble
## Loading tidyverse: tidyr
## Loading tidyverse: readr
## Loading tidyverse: purrr
## Loading tidyverse: dplyr
## Conflicts with tidy packages ----------------------------------------------
## filter(): dplyr, stats
## lag():    dplyr, stats
library(sf)
## Linking to GEOS 3.5.0, GDAL 2.1.1, proj.4 4.9.3
library(scsf)
## Loading required package: sc
nc = st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE)
x <- PRIMITIVE(nc)


## this function uniquifies the segments, very much WIP
u_edges <- function(x, ...) UseMethod("u_edges")
u_edges.PRIMITIVE <- function(x, ...) {
  u_edges(x[["segment"]])
}
u_edges.data.frame <- function(x, ...) {
  u2 <- x %>%         mutate(uu = paste(pmin(.vertex0, .vertex1), pmax(.vertex0, .vertex1), sep = "_"))
  #dplyr::distinct(select(u2, uu, segment_), uu,  .keep_all = TRUE)
  select(u2, uu, segment_)
}


set.seed(100)
nc$colour <- sample(viridis::viridis(100))

## filter to the 50th
x50 <- x$object[50, "object_"] %>% inner_join(x$path) %>% 
  inner_join(x$path_link_vertex) %>% 
  inner_join(x$vertex)
## Joining, by = "object_"
## Joining, by = "path_"
## Joining, by = "vertex_"
## join by vertex 
idx_vertex <- x50 %>% dplyr::select(vertex_) %>% 
  inner_join(x$path_link_vertex, "vertex_") %>% 
  inner_join(x$path) %>% 
  distinct(object_) ##%>% inner_join(nc %>% mutate(object_ = x$object_))
## Joining, by = "path_"
v_idx <- match(idx_vertex$object_, x$object$object_)


## join the subset data to the main on unique segment 
## (unique as in order of vertices is irrelevant)
idx_edge <- u_edges.data.frame(x$object[50, "object_"] %>% 
                                 inner_join(x$path) %>% 
                                 inner_join(x$segment)) %>%  
  select(-segment_) %>% inner_join(u_edges.PRIMITIVE(x), "uu") %>% 
  inner_join(x$segment) %>% inner_join(x$path) %>% 
  distinct(object_)
## Joining, by = "object_"
## Joining, by = "path_"
## Joining, by = "segment_"
## Joining, by = "path_"
e_idx <- match(idx_edge$object_, x$object$object_)

par(mfrow = c(3, 1), mar = c(rep(0.75, 4)))

# Target county
plot(nc[1], col = "firebrick", main = "Target county")
plot(nc[50, 1], add = TRUE, col = nc$colour[50])

plot(nc[, 1], col = "firebrick", main = "Edge share"); plot(nc[e_idx, 1], add = TRUE, col = nc$colour[e_idx])
plot(nc[, 1], col = "firebrick", main = "Vertex share"); plot(nc[v_idx, 1], add = TRUE, col = nc$colour[v_idx])

print(e_idx)
## [1] 69 50 39 40 42 71