library(tidyverse)
ALL_PARCEL_DATA <- read_csv("Data/Crop_Parcel_Data/WELL_DITCH_PARCEL.csv")
NAMES <- colnames(ALL_PARCEL_DATA )
PARCEL_LINK <- ALL_PARCEL_DATA %>% select(NAMES[grep("PARCEL_ID|GW_ID|SW_WDID",NAMES )])
PARCEL_LINK <- PARCEL_LINK  %>% pivot_longer(-PARCEL_ID,values_to='wdid',names_to="type") %>% filter(!is.na(wdid)) 
PARCEL_LINK$type <- ifelse(grepl("SW",PARCEL_LINK$type ),"SW","GW")

WELL <- PARCEL_LINK %>% filter(type=='GW') %>% select(-type) %>% unique
DITCH <- PARCEL_LINK %>% filter(type=='SW') %>% rename(ditch_id=wdid) %>% select(-type) %>% unique

DITCH_WELL <- WELL %>% inner_join(DITCH) %>% select(-PARCEL_ID) %>% unique

#TOP_20 <- 	(DITCH_WELL %>% group_by(ditch_id) %>% summarize(num=n()) %>% arrange(desc(num)))[1:20,] %>% pull(ditch_id)
#DITCH_WELL$ditch_id[!(DITCH_WELL$ditch_id %in% TOP_20) ] <- "Other"
DITCH_WELL <- DITCH_WELL  %>% unique
DITCH_WELL <- DITCH_WELL %>% pivot_wider(values_from=ditch_id,names_from=ditch_id,names_prefix="ditch_")
DITCH_WELL[,-1] <- ifelse(is.na(DITCH_WELL[,-1]),0,1)
DITCH_WELL <- DITCH_WELL %>% mutate(wdid=as.character(wdid))

saveRDS(DITCH_WELL,"Data/Crop_Parcel_Data/Well_Ditch_Link.rds")
print("Script 2: Process ditch link data completed")

