#' @title Weather Station Statistics
#' 
#' @description Download weather data from the National Centers for Environmental Information (NCEI) using their API. 
#' 
#' @param FAAID Federal Aviation Administration (FAA) station ID 
#' @param year year for which data are to be downloaded
#' @param startDate start date in YY-MM-DD format
#' @param endDate end date in YY-MM-DD format 
#' @param trimNA remove days with no data 
#' @param maxTries maximum number of query attempts to the NCEI server 
#' @param tpause time in seconds to pause between API requests 
#' @param verbose a logical value indicating whether to report download progress
#' 
#' @return a data frame with daily weather data 
#'
#' @author Peter Hoff
#' 
#' @examples   
#' \donttest{
#' RDU<-weatherStats("RDU",startDate="2024-01-01",endDate="2025-12-31") 
#' SEA<-weatherStats("SEA",year=2025)   
#' }
#'  
#' dim(RDU) 
#' dim(SEA) 
#' colnames(SEA)
#'  
#' @export
weatherStats<-function(FAAID,
  year=NULL,startDate=NULL,endDate=NULL,trimNA=TRUE,maxTries=5,tpause=3,verbose=TRUE){ 

  ## dates 
  if(is.null(year) & is.null(startDate)){ year<-format(Sys.time(),"%Y") }
  if(is.null(startDate)){ startDate=paste0(year,"-01-01") } 
  if(is.null(endDate)){ endDate=paste0(substr(startDate,1,4),"-12-31") }

  ## convert FAA ID to station ID
  stationID<-STATIONS$GHCND[which(STATIONS$FAA==FAAID)]

  ## construct API query  
  query<-paste0("https://www.ncei.noaa.gov/access/services/data/v1?dataset=daily-summaries",
                "&stations=",stationID, 
                "&startDate=",startDate,
                "&endDate=",endDate,
                "&includeStationLocation=true&units=metric")  

  ## read data 
  numTries<-1 
  dat<-try(suppressWarnings(read.csv(query)),silent=TRUE)
  while(attr(dat,"class")=="try-error" & numTries<maxTries){  
    if(verbose){ cat("Query attempt",numTries,"failed\n") }
    Sys.sleep(tpause) 
    dat<-try(suppressWarnings(read.csv(query)),silent=TRUE)
    numTries<-numTries+1 
  } 

  if(attr(dat,"class")=="try-error"){ dat<-NULL } 

  if(!is.null(dat)){  
    ## change station id to FAA id
    dat$STATION<-FAAID  

    ## remove dates with no data
    if(trimNA){ dat<-dat[,apply(!is.na(dat),2,any )] } 
  }

  dat
}


