##################################################################
# 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 ##
#                                                               ##
##################################################################
message("Begin prepare_handoff_files")

suppressPackageStartupMessages(library(tidyr))

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

vars <- NULL
for (i in seq_along(sites)) {
  if(nchar(sites[i]) > 1) {
    print(pot_vars[i])
    vars <- c(vars, pot_vars[i])
  }
}

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
  if(!dir.exists('handoff_files')) dir.create('handoff_files', recursive = TRUE)
  sapply(names(trnd_reformat), 
         function (x) write.csv(trnd_reformat[[x]]
                                , file = paste('handoff_files/', res_abb, '_', x, '.csv', sep='')
                                , row.names = F))
}

message("prepare_handoff_files complete")