#' @include internals.R
NULL

#' Build a formula from a \code{procmod_frame}.
#'
#' The first element of the \code{procmod_frame}
#' is used as the variable to  explain. The others
#' elements of the \code{procmod_frame} is considered
#' as explanatory variables.
#'
#' @param x the \code{procmod_frame} to be used
#' @param ... further arguments passed to or from other methods.
#'
#' @return produces an object of class \code{\link[stats]{formula}} which
#'         contains a symbolic model formula.
#'
#' @examples
#' A <- simulate_matrix(20, 5)
#' B <- simulate_correlation(A, 10, r2 = 0.4)
#' C <- simulate_correlation(A, 15, r2 = 0.6)
#'
#' pf <- procmod_frame(A = A, B = B, C = C)
#'
#' formula(pf)
#'
#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
formula.procmod_frame <- function(x, ...) {
  nm <- sapply(names(x), as.name)

  if (length(nm) > 1L) {
    rhs <- nm[-1L]
    lhs <- nm[1L]
  }
  else if (length(nm) == 1L) {
    rhs <- nm[1L]
    lhs <- NULL
  }
  else {
    stop("cannot create a formula from an empty procmod.frame")
  }

  ff <- parse(
    text = paste(lhs,
      paste(rhs,
        collapse = "+"
      ),
      sep = "~"
    ),
    keep.source = FALSE
  )

  ff <- eval(ff)

  environment(ff) <- parent.frame()

  ff
}
