#' Summary method for objects of class "mglm.test"
#' @param object An \code{mglm.test} object.
#' @param ... Additional arguments that could be passed to \code{summary.mglm.test}.
#'
#' @return An object with S3 class \code{summary.mglm.test}. The class has its own print
#' method and contains the following list of elements.
#' \item{sum.ERE}{The summary table of point estimate and confidence interval
#' of ERE for each modality.}
#' \item{sum.R2}{The summary table of point estimate and confidence interval
#' of pseudo-\eqn{R^2} for each modality.}
#' \item{conf.level}{ Level of confidence intervals.}
#' \item{sel.mod}{ Index of the most informative modality.}
#' @export
summary.mglm.test <- function(object, ...) {
  args_extra <- list(...)
  nmod <- length(object$num.nonzeros)

  ## Checke if there is only one informative modality
  ixnum <- sapply(object$sel.idx,length)
  if(sum(ixnum==0) == nmod-1){
    k = order(ixnum,decreasing = TRUE)[1]
  }else{
    if(sum(ixnum)==0) {
      k = 0
    } else {
      k = order(object$ERE,decreasing=TRUE)[1]
    }
  }
  est_ERE <- data.frame(estimate = object$ERE,
                        lower.bound = object$ERE.CI.L,
                        upper.bound = object$ERE.CI.U,
                        row.names = paste("Modality",seq(1:nmod))
  )
  est_R2 <- data.frame(estimate = object$R2,
                       lower.bound = object$R2.CI.L,
                       upper.bound = object$R2.CI.U,
                       row.names = paste("Modality",seq(1:nmod))
  )

  summary_data <- list(sum.ERE = est_ERE, sum.R2 = est_R2, conf.level = object$conf.level,
                       sel.mod = k)
  class(summary_data) <- "summary.mglm.test"
  return(summary_data)

}


#' @param x  A \code{summary.mglm.test} object.
#'
#' @rdname summary.mglm.test
#' @export
print.summary.mglm.test <- function(x, ...) {
  if(x$sel.mod == 0){
    cat("No variable selected. \n\n")
  }else{
    cat("The most informative modality is modality", x$sel.mod, ".\n\n")
  }

  cat("Summary of mglm.test result:\n\n")
  cat("Expected Relative Entropy:\n\n")
  print(format(x$sum.ERE, digits = 4, justify = "right"))
  cat("The confidence level =", 100*x$conf.level,"% \n\n")

  cat("Pseudo R2:\n")
  print(format(x$sum.R2, digits = 4, justify = "right"))
  cat("The confidence level =", 100*x$conf.level,"% \n\n")
  invisible(x) # Return the object invisibly
}
