
#' @title Get CitizenAir Stations
#' @description Get CitizenAir Stations
#' @param x an object of class \code{Endpoint} as returned by \code{as.Endpoint}
#' @export
#' @return 
#' an object of class \code{citizenair_stations} which is a list with elements \code{phenomena} and \code{stations}\cr
#' Element phenomena is a data.table with all phenomena containing fields
#' \enumerate{
#' \item{id: identifier of the phenomena}
#' \item{label: label of the phenomena}
#' }
#' Element stations is a data.table with all stations containing fields
#' \enumerate{
#' \item{id: identifier of the station}
#' \item{label: label of the station}
#' \item{lon: longitude of the station}
#' \item{lat: latitude of the station}
#' \item{phenomena: a list of phenomena identifiers for each station}
#' \item{phenomena_label: a list of phenomena labels for each station}
#' \item{timeseries: a list of timeseries identifiers for each station}
#' }
#' @examples 
#' library(sensorweb4R)
#' e <- as.Endpoint("http://geo.irceline.be/sos/api/v1")
#' x <- read_stations(e)
read_stations <- function(x = sensorweb4R::as.Endpoint("http://geo.irceline.be/sos/api/v1")){
  stopifnot(inherits(x, "Endpoint"))
  e <- x
  url <- sensorweb4R::resourceURL(e)
  
  phe <- data.table(id = sensorweb4R::id(sensorweb4R::phenomena(e)),
                    label = sensorweb4R::label(sensorweb4R::phenomena(e)), 
                    stringsAsFactors = FALSE)
  phe <- phe[order(phe$label, decreasing = FALSE), ]

  ## Query http://geo.irceline.be/sos/api/v1/stations?expanded=true
  sta <- httr::GET(url = sprintf("%s/%s", url, "stations"), query = list(expanded="true"))
  sta <- httr::content(sta)
  sta <- lapply(sta, FUN=function(x){
    out <- list(id = x$properties$id, 
               label = x$properties$label, 
               lon = x$geometry$coordinates[[1]], 
               lat = x$geometry$coordinates[[2]], 
               phenomena = sort(unique(sapply(x$properties$timeseries, FUN=function(x) x$phenomenon$id))),
               timeseries = sort(unique(names(x$properties$timeseries))))
    out
  })
  stat <- rbindlist(lapply(sta, FUN=function(x) x[c("id", "label", "lon", "lat")]))
  stat$phenomena <- lapply(sta, FUN=function(x) x$phenomena)
  stat$phenomena_label <- lapply(sta, FUN=function(x) txt_recode(x$phenomena, from = phe$id, to = phe$label))
  stat$timeseries <- lapply(sta, FUN=function(x) x$timeseries)
  result <- list()
  result$phenomena <- phe
  result$phenomena$label <- iconv(result$phenomena$label, from = "UTF-8", to = "LATIN1")
  result$stations <- stat
  class(result) <- "citizenair_stations"
  result
}