#' Estimation of the AUC of logistic regression models with complex survey data.
#'
#' Calculate the AUC of a logistic regression model
#' considering sampling weights with complex survey data
#' @param response.var A character string with the name of the column indicating the response variable in the data set
#' or a vector (either numeric or character string) with information of the response variable for all the units.
#' @param phat.var A character string with the name of the column indicating the estimated probabilities in the data set
#' or a numeric vector containing estimated probabilities for all the units.
#' @param weights.var A character string indicating the name of the column with sampling weights or
#' a numeric vector containing information of the sampling weights.
#' It could be \code{NULL} if the sampling design is indicated in the \code{design} argument.
#' For unweighted estimates, set all the sampling weight values to 1.
#' @param tag.event A character string indicating the label used to indicate the event of interest in \code{response.var}.
#' The default option is \code{tag.event = NULL}, which selects the class with the lowest number of units as event.
#' @param tag.nonevent A character string indicating the label used for non-event in \code{response.var}.
#' The default option is \code{tag.nonevent = NULL}, which selects the class with the greatest number of units as non-event.
#' @param data A data frame which, at least, must incorporate information on the columns
#' \code{response.var}, \code{phat.var} and \code{weights.var}.
#' If \code{data=NULL}, then specific numerical vectors must be included in
#' \code{response.var}, \code{phat.var} and \code{weights.var},
#' or the sampling design should be indicated in the argument \code{design}.
#' @param design An object of class \code{survey.design} generated by
#' \code{survey::svydesign} indicating the complex sampling design of the data.
#' If \code{design = NULL}, information on the data set (argument \code{data})
#' and/or sampling weights (argument \code{weights.var}) must be included.
#'
#' @return The output object of this function is a list of 4 elements containing the following information:
#' - `AUCw`: the weighted estimate of the AUC.
#' - `tags`: a list containing two elements with the following information:
#'    - `tag.event`: a character string indicating the event of interest.
#'    - `tag.nonevent`: a character string indicating the non-event.
#' - `basics`: a list containing information of the following 4 elements:
#'    - `n.event`: number of units with the event of interest in the data set.
#'    - `n.nonevent`: number of units without the event of interest in the data set.
#'    - `hatN.event`: number of units with the event of interest represented in the population by all the event units in the data set, i.e., the sum of the sampling weights of the units with the event of interest in the data set.
#'    - `hatN.nonevent`: a numeric value indicating the number of non-event units in the population represented by means of the non-event units in the data set, i.e., the sum of the sampling weights of the non-event units in the data set.
#' - `call`: an object saving the information about the way in which the function has been run.
#'
#' @details
#' \eqn{S} indicate a sample of \eqn{n} observations of the vector of random variables \eqn{(Y,\pmb X)}, and \eqn{\forall i=1,\ldots,n,} \eqn{y_i} indicate the \eqn{i^{th}} observation of the response variable \eqn{Y},
#' and \eqn{\pmb x_i} the observations of the vector covariates \eqn{\pmb X}. Let \eqn{w_i} indicate the sampling weight corresponding to the unit \eqn{i} and \eqn{\hat p_i} the estimated probability of event.
#' Let \eqn{S_0} and \eqn{S_1} be subsamples of \eqn{S}, formed by the units without the event of interest (\eqn{y_i=0}) and with the event of interest (\eqn{y_i=1}), respectively.
#' Then, the AUC is estimated as follows:
#' \deqn{\widehat{AUC}_w=\dfrac{\sum_{j\in S_0}\sum_{k\in S_1}w_jw_k \{I(\hat p_j < \hat p_k) + 0.5\cdot I(\hat p_j = \hat p_k)\}}{\sum_{j\in S_0}\sum_{k\in S_1}w_jw_k}.}
#' See Iparragirre et al (2023) for more information.
#'
#' @references Iparragirre, A., Barrio, I. and Arostegui, I. (2023).
#' Estimation of the ROC curve and the area under it with complex survey data.
#' *Stat* **12**(1), e635. (https://doi.org/10.1002/sta4.635)
#'
#' @export
#'
#' @examples
#' data(example_data_wroc)
#'
#' auc.obj <- wauc(response.var = "y",
#'                 phat.var = "phat",
#'                 weights.var = "weights",
#'                 tag.event = 1,
#'                 tag.nonevent = 0,
#'                 data = example_data_wroc)
#'
#' # Or equivalently
#' auc.obj <- wauc(response.var = example_data_wroc$y,
#'                 phat.var = example_data_wroc$phat,
#'                 weights.var = example_data_wroc$weights,
#'                 tag.event = 1, tag.nonevent = 0)
#'
wauc <- function(response.var, phat.var, weights.var = NULL, tag.event = NULL, tag.nonevent = NULL, data = NULL, design = NULL){

  if(!is.null(design)){
    data <- get(design$call$data)
    weights <- as.character(design$call$weights[2])
    weights.var <- data[,weights]
  }
  
  if(inherits(response.var, "character")){
    response.var <- data[,response.var]
  }

  if(length(table(response.var))!=2){stop("Response variable must have two classes.")}
  

  if(inherits(phat.var, "character")){
    phat.var <- data[,phat.var]
  }

  if(inherits(weights.var, "character")){
    weights.var <- data[,weights.var]
  }

  if(length(response.var) != length(phat.var) || length(response.var) != length(weights.var)){
    stop("Vectors indicating the responses, predicted probabilities and sampling weights must be the same length.")
  }

  # Missing tags:
  if(is.null(tag.nonevent)){
    if(is.null(tag.event)){
      tag.nonevent <- names(table(response.var)[which.max(table(response.var))])
      tag.event <- names(table(response.var)[which.min(table(response.var))])
    } else {
      tags <- names(table(response.var))
      tag.other <- which(tags == tag.event)
      tag.nonevent <- tags[-tag.other]
    }
  } else {
    if(is.null(tag.event)){
      tags <- names(table(response.var))
      tag.other <- which(tags == tag.nonevent)
      tag.event <- tags[-tag.other]
    }
  }


  p0 <- phat.var[which(response.var==tag.nonevent)]
  p1 <- phat.var[which(response.var==tag.event)]

  w0 <- weights.var[which(response.var==tag.nonevent)]
  w1 <- weights.var[which(response.var==tag.event)]

  auc <- (sum(outer(w1, w0, "*")[which(outer(p1, p0, ">"))]) + 0.5*sum(outer(w1, w0, "*")[which(outer(p1, p0, "=="))]))/(sum(w0)*sum(w1))


  auc.obj <- list()
  auc.obj$AUCw <- auc
  auc.obj$tags <- list(tag.event = as.character(tag.event),
                       tag.nonevent = as.character(tag.nonevent))
  auc.obj$basics <- list(n.event = length(which(response.var==tag.event)),
                         n.nonevent = length(which(response.var==tag.nonevent)),
                         hatN.event = sum(w1),
                         hatN.nonevent = sum(w0))
  auc.obj$call <- match.call()


  return(auc.obj)

}


