#==========================================================
# Missing Value Check
#==========================================================

#' Check Missing Values
#'
#' Examines each variable in a dataset and reports the
#' number and percentage of missing and complete values.
#'
#' @param data A data.frame.
#'
#' @return A data.frame of class \code{MissingCheck}
#'   containing variable-level missing-value information.
#'
#' @details
#' For each variable, the function reports the total number
#' of observations, number of missing values, number of
#' complete values, and their corresponding percentages.
#'
#' Missing values are identified using \code{is.na()}.
#'
#' @examples
#' missing_check(iris)
#'
#' dat <- iris
#' dat$Sepal.Length[1:10] <- NA
#' dat$Species[1:5] <- NA
#' missing_check(dat)
#'
#' @export

missing_check <- function(data) {

  #---------------------------------------------
  # Validation
  #---------------------------------------------
  validate_data(data)

  #---------------------------------------------
  # Dataset size
  #---------------------------------------------
  n <- nrow(data)

  #---------------------------------------------
  # Missing counts
  #---------------------------------------------
  missing <- vapply(
    data,
    function(x) sum(is.na(x)),
    integer(1)
  )

  #---------------------------------------------
  # Complete counts
  #---------------------------------------------
  complete <- n - missing

  #---------------------------------------------
  # Percentages
  #---------------------------------------------
  if (n == 0L) {

    missing_percent <- rep(
      NA_real_,
      ncol(data)
    )

    complete_percent <- rep(
      NA_real_,
      ncol(data)
    )

  } else {

    missing_percent <- 100 * missing / n

    complete_percent <- 100 * complete / n

  }

  #---------------------------------------------
  # Result
  #---------------------------------------------
  result <- data.frame(

    Variable = names(data),

    Total = rep(
      n,
      ncol(data)
    ),

    Missing = unname(missing),

    Complete = unname(complete),

    MissingPercent = round(
      unname(missing_percent),
      2
    ),

    CompletePercent = round(
      unname(complete_percent),
      2
    ),

    stringsAsFactors = FALSE,

    check.names = FALSE
  )

  #---------------------------------------------
  # Class
  #---------------------------------------------
  class(result) <- c(
    "MissingCheck",
    "data.frame"
  )

  result
}
