##############################################################################################
#' @title Compute combined and expanded (95% confidence) temporally aggregated L1 uncertainty 
#' due to natural variation, calibration (multiplier), and voltage-based FDAS measurement

#' @author
#' Cove Sturtevant \email{csturtevant@battelleecology.org}

#' @description
#' Wrapper function. Compute the combined and expanded (95% confidence) temporally aggregated L1 
#' uncertainty for a set of values subject to natural variation, calibration uncertainty, and 
#' voltage-based FDAS uncertainty. Uncertainty due to  natural variation is estimated from the 
#' standard error of the mean. Uncertainty due to calibration is represented by a multiplier 
#' (U_CVALA3 (%) coefficient provided by CVAL) to the maximum L0' value. Uncertainty due to 
#' voltage-based FDAS measurement is computed from NEONprocIS.stat::def.ucrt.dp01.fdas.

#' @param data Data frame of L0' (calibrated) data. Must contain columns \code{readout_time} (POSIX) and 
#' whatever variable is specified in input parameter \code{VarUcrt} (numeric).
#' A single aggregated uncertainty for the selected variable \code{VarUcrt} will be computed over the full timeseries.
#' @param VarUcrt A character string of the target variable (column) in the data frame \code{data} for 
#' which uncertainty data will be computed (all other columns will be ignored in this function). 
#' @param ucrtCoef A list of uncertainty coefficients, each a list containing at a minimum the list 
#' elements: term (name of L0' term for which the coefficient applies - string), start_date (POSIX), 
#' end_date(POSIX), Name (of the coefficient - string), and 
#' Value (of the coefficient - string or numeric, to be interpreted as numeric). 
#' This will be passed into the calibration and FDAS uncertainty functions. Calibration uncertainty 
#' requires the U_CVALA3 coefficient. Voltage-based FDAS uncertainty requires U_CVALV3 and U_CVALV4 
#' coefficients.
#' @param ucrtData A data frame of L0' individual measurement uncertainty data generated by the 
#' calibration step. This will be passed into the FDAS uncertainty function NEONprocIS.stat::def.ucrt.dp01.fdas. 
#' See that function's inputs for required columns.
#' @param log A logger object as produced by NEONprocIS.base::def.log.init to produce structured log
#' output. Defaults to NULL, in which the logger will be created and used within the function.

#' @return A single numeric value representing the aggregated L1 calibration uncertainty over the full record. 
#' Numeric NA is returned if no applicable coefficient is found, with warning.

#' @references
#' License: (example) GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007
#' NEON.DOC.000785 TIS Level 1 Data products Uncertainty Budget Estimation Plan
#' NEON.DOC.000746 Calibration Fixture and Sensor Uncertainty Analysis: CVAL 2014 Uncertainty Manual

#' @keywords calibration, uncertainty, fdas L1, average

#' @examples
#' data <- data.frame(readout_time=as.POSIXct(c('2019-01-01 00:00','2019-01-01 00:01','2019-01-01 00:02'),tz='GMT'),
#'                    linePAR=c(827.7,827.8,831.3))
#' ucrtCoef <- list(list(term='linePAR',start_date=as.POSIXct('2019-01-01',tz='GMT'),end_date=as.POSIXct('2019-01-02',tz='GMT'),Name='U_CVALA3',Value='0.0388'),
#'                  list(term='linePAR',start_date=as.POSIXct('2019-01-01',tz='GMT'),end_date=as.POSIXct('2019-01-02',tz='GMT'),Name='U_CVALV3',Value='0.000374'),
#'                  list(term='linePAR',start_date=as.POSIXct('2019-01-01',tz='GMT'),end_date=as.POSIXct('2019-01-02',tz='GMT'),Name='U_CVALV4',Value='0.0000020'))
#' ucrtData <- data.frame(readout_time=as.POSIXct(c('2019-01-01 00:00','2019-01-01 00:01','2019-01-01 00:02'),tz='GMT'),
#'                        linePAR_raw=c(0.0064085,0.006409,0.0064097),
#'                        linePAR_dervCal=c(129153.7,129153.7,129153.7),
#'                        linePAR_ucrtComb=c(0.57992,0.57998,0.57998),
#'                        stringsAsFactors=FALSE)
#' ucrt <- NEONprocIS.stat::wrap.ucrt.dp01.cal.mult.fdas.volt(data=data,VarUcrt='linePAR',ucrtCoef=ucrtCoef,ucrtData=ucrtData)

#' @seealso \link[NEONprocIS.stat]{wrap.ucrt.dp01}
#' @seealso \link[NEONprocIS.stat]{def.ucrt.dp01.cal.mult}
#' @seealso \link[NEONprocIS.stat]{def.ucrt.dp01.fdas}

#' @export

# changelog and author contributions / copyrights
#   Cove Sturtevant (2020-10-27)
#     original creation
##############################################################################################
wrap.ucrt.dp01.cal.mult.fdas.volt <- function(data,
                                              VarUcrt,
                                              ucrtCoef,
                                              ucrtData,
                                              log = NULL) {
  # Initialize logging if necessary
  if (base::is.null(log)) {
    log <- NEONprocIS.base::def.log.init()
  }
  
  # Validate the data. Need columns readout_time and VarUcrt
  chk <- NEONprocIS.base::def.validate.dataframe(dfIn=data,TestNameCol=c('readout_time',VarUcrt),TestEmpty=FALSE, log = log)
  if (!chk) {
    stop()
  }
  
  # Pull the variable from data that we care about
  dataComp <- data[[VarUcrt]]
  
  # Check data input is numeric
  if (!NEONprocIS.base::def.validate.vector(dataComp,TestEmpty = FALSE, TestNumc = TRUE, log=log)) {
    stop()
  }
  
  # Compute uncertainty of the mean due to natural variation, represented by the standard error of the mean
  #log$debug(base::paste0('Computing L1 uncertainty due to natural variation (standard error)'))
  numPts <- base::sum(x=!base::is.na(dataComp),na.rm=FALSE)
  se <- stats::sd(dataComp,na.rm=TRUE)/base::sqrt(numPts)
  
  # Compute calibration uncertainty (constant value from CVAL coefficient U_CVALA3)
  ucrtCal <- NEONprocIS.stat::def.ucrt.dp01.cal.mult(data=dataComp,
                                                     ucrtCoef=ucrtCoef,
                                                     NameCoef='U_CVALA3',
                                                     VarUcrt=VarUcrt,
                                                     TimeAgrBgn=data$readout_time[1],
                                                     TimeAgrEnd=data$readout_time[base::nrow(data)]+as.difftime(.001,units='secs'),
                                                     log=log)
  
  # Compute FDAS uncertainty (for one resistance channel reading)
  ucrtFdas <- NEONprocIS.stat::def.ucrt.dp01.fdas(data=dataComp,
                                                  VarUcrt=VarUcrt,
                                                  TypeFdas='V',
                                                  ucrtCoef=ucrtCoef,
                                                  ucrtData=ucrtData,
                                                  log=log)
                     
  # Compute combined and expanded uncertainty
  ucrt=2*base::sqrt(se^2 + ucrtCal^2 + ucrtFdas^2) 
  
  return(ucrt)
  
}
