##################################################################
# This script takes seasonal kendall results for                ##
# WQ, MET, and NUT data and reformats it for later use with     ##
# with national level template. Reserve-level users             ##
# should not need to use this file.                             ##
#                                                               ##
# The number of files generated by this file will match the     ##
# number of parameters in the reserve level variable input file ##
#                                                               ##
##################################################################
library(tidyr)

vars <- c('wq', 'met', 'nut')
sites <- list(wq_sites, met_sites, nut_sites)

for(i in 1:length(vars)){
  
  data_loc <- paste('output/', vars[i], sep = '')
  # Load WQ seasonal Kendall results
  trnd <- read.csv(paste(data_loc,  '/trend_sk/', res_abb, '_', vars[i], '_seasonal_kendall_results_reformat.csv', sep = ''))
  
  # reformat for national report
  trnd_reformat <- gather(trnd, parameter, trend, 2:length(names(trnd))) %>% 
    spread(., station, trend)
  
  # rename columns
  names(trnd_reformat) <- c('Reserve', paste0('LOC ', c(1:length(sites[[i]]))))
  
  # split data frame into list of data frames by parameter
  trnd_reformat <- split(trnd_reformat, f = trnd_reformat$Reserve)
  
  # replace parameter name with the reserve name
  trnd_reformat <- lapply(trnd_reformat, function(x) {x$Reserve <- res; x})
  
  # print each data.frame in the list
  sapply(names(trnd_reformat), 
         function (x) write.csv(trnd_reformat[[x]]
                                , file = paste('handoff_files/', res_abb, '_', x, '.csv', sep='')
                                , row.names = F))
}
