
library(s2dv)
library(multiApply)

CorrEno <- function(exp, obs, time_dim = 'year', member_dim = NULL, method = 'pearson', alpha = 0.05, pval = FALSE, na.rm = FALSE, ncores = 1){
  
  ## Ensemble mean
  if (!is.null(member_dim)){
    exp <- multiApply::Apply(data = exp, target_dims = member_dim, fun = mean, na.rm = na.rm, ncores = ncores)$output1
  }
  
  ## Correlation coefficient and its significance
  output <- multiApply::Apply(data = list(exp = exp, obs = obs), target_dims = time_dim, 
                              fun = .correlation_eno, time_dim = time_dim, method = method, 
                              alpha = alpha, pval = pval, na.rm = na.rm, ncores = ncores)
  return(output)
}

.correlation_eno <- function(exp, obs, time_dim, method, alpha, pval, na.rm){
  
  if (isTRUE(na.rm)){
    use <- 'pairwise.complete.obs'
  } else {use <- 'everything'}
  
  cor <- NULL
  cor$r = cor(x = exp, y = obs, method = method, use = use) # Correlation coefficient
  
  n_eff = s2dv::Eno(data = obs, time_dim = time_dim, na.action = na.pass, ncores = 1)
  t_alpha2_n2 = qt(p=alpha/2, df = n_eff-2, lower.tail = FALSE)
  t = abs(cor$r) * sqrt(n_eff-2) / sqrt(1-cor$r^2)
  
  if (anyNA(c(t,t_alpha2_n2)) == FALSE & t >= t_alpha2_n2){
    cor$sign = TRUE
  } else {
    cor$sign = FALSE
  }
  
  cor$n_eff <- n_eff
  
  if (isTRUE(pval)){
    cor$pval <- 2 * pt(q = t, df = n_eff-2, lower.tail = FALSE)
  }
  
  return(cor)
}
