#' @title sweden
#' @name sweden
#'
#' @description Retrieve Swedish gauge data
#'
#' @param site sweden gauge number
#' @param variable Character. Either `stage` or `discharge`.
#' @param start_date Character. Optional start date with format
#'   YYYY-MM-DD. Default is 1900-01-01.
#' @param end_date Character. End date with format YYYY-MM-DD.
#'   Default is the current date.
#' @param sites Logical. If TRUE, returns a list of measurement
#'   sites.
#' @param ... Additional arguments. None implemented.
#'
#' @return data frame of discharge time-series
#' @examples
#' \donttest{
#' df = sweden(site='2000',variable='discharge')
#' plot(df$Date,df$Q,type='l')
#' }
#' @importFrom data.table fread
#' @export
sweden <- function(site,
                   variable,
                   start_date = NULL,
                   end_date = NULL,
                   sites = FALSE,
                   ...) {

  if (sites) {
    return(sweden_sites)
  }
  start_date <- .get_start_date(start_date)
  end_date <- .get_end_date(end_date)
  column_name <- .get_column_name(variable)
  original_data <- try(download_sweden_data(
    site, variable, start_date, end_date
  ),silent=TRUE)
  if(is.error(original_data)==TRUE|length(original_data)==0){stop('This gauge does not have a record associated with it and/or the agency website is down.')}
  data <- original_data

  data <- data%>%dplyr::select(all_of(c("date", "value"))) %>%
    rename(Date = "date", !!column_name := "value")
  if(variable=='stage'){
    data$H = data$H*.01
  }
  out <- new_tibble(
    data,
    original = original_data,
    class = "rr_tbl"
  )
  return(out)
}

download_sweden_data = function(site, variable, start_date, end_date){
  if (variable == "stage") {
    site=paste0('https://opendata-download-hydroobs.smhi.se/api/version/1.0/parameter/3/station/',site,'/period/corrected-archive/data.json')
  } else if (variable == "discharge") {
    site=paste0('https://opendata-download-hydroobs.smhi.se/api/version/1.0/parameter/1/station/',site,'/period/corrected-archive/data.json')
  }
  data = fromJSON(site)
  ts = data$value
  ts$date = as.Date(as.POSIXct(ts$date/1000, origin='1970-01-01'))

  original_data <- ts[ts$date>=as.Date(start_date)&ts$date<=as.Date(end_date),]
  return(original_data)
}

