library(osmdata)
library(sf)
library(magrittr)
library(dplyr)
library(tidyr)
library(ggplot2)

##############################
## Arventennoù
# Cheñch teuliad
source_path <- rstudioapi::getActiveDocumentContext()$path
setwd(dirname(dirname(source_path)))


## Kemer an data
# An harzoù
if (!file.exists("./tmp/kumuniou.RData")) {
  kumuniou_22 <- opq(bbox="Côtes-d'Armor") %>%
    add_osm_feature(key = 'boundary', value = 'administrative') %>%
    add_osm_feature(key = 'admin_level', value = '8') %>%
    osmdata_sf
  kumuniou_29 <- opq(bbox="Finistère") %>%
    add_osm_feature(key = 'boundary', value = 'administrative') %>%
    add_osm_feature(key = 'admin_level', value = '8') %>%
    osmdata_sf
  kumuniou_56 <- opq(bbox="Morbihan") %>%
    add_osm_feature(key = 'boundary', value = 'administrative') %>%
    add_osm_feature(key = 'admin_level', value = '8') %>%
    osmdata_sf
  
  kumuniou <- c(kumuniou_22,
                kumuniou_29,
                kumuniou_56
  ) %>% unique_osmdata
  
  kumuniou_poly <- kumuniou$osm_multipolygons
  kumuniou_poly <- kumuniou_poly %>%
    mutate(ref.INSEE = as.numeric(as.character(ref.INSEE))) %>%
    filter(grepl("^(22|29|56)", ref.INSEE))
  
  
  ggplot(kumuniou_poly)+
    geom_sf()
  
  
  dept_22 <- opq(bbox = "Côtes-d'Armor") %>%
    add_osm_feature(key = 'boundary', value = 'administrative') %>%
    add_osm_feature(key = 'admin_level', value = '6') %>%
    osmdata_sf %>% unique_osmdata
  dept_29 <- opq(bbox = "Finistère") %>%
    add_osm_feature(key = 'boundary', value = 'administrative') %>%
    add_osm_feature(key = 'admin_level', value = '6') %>%
    osmdata_sf %>% unique_osmdata
  dept_56 <- opq(bbox = "Morbihan") %>%
    add_osm_feature(key = 'boundary', value = 'administrative') %>%
    add_osm_feature(key = 'admin_level', value = '6') %>%
    osmdata_sf %>% unique_osmdata
  
  dept <- c(dept_22, dept_29, dept_56) %>%
    unique_osmdata
  
  dept_poly <- dept$osm_multipolygons
  dept_poly <- dept_poly %>%
    filter(grepl("^(22|29|56)", ref.INSEE))
  
  
  save(kumuniou, kumuniou_poly,
       dept, dept_poly, 
       file = "./tmp/kumuniou.RData")
} else {
  load(file = "./tmp/kumuniou.RData")
}

kumuniou_poly_simple <- st_simplify(kumuniou_poly, preserveTopology = TRUE, dTolerance = 0.001)
dept_poly_simple <- st_simplify(dept_poly, preserveTopology = TRUE, dTolerance = 0.001)