#' @title
#' Computing the intersection of a collection of posets.
#'
#' @description
#' Computes the poset \eqn{(V, \leq_{\cap})=(V, \leq_1)\cap\cdots\cap(V,\leq_k)}.
#'
#' @param poset1 An object of S4 class `POSet`.
#' Argument `poset1` must be created by using any function contained in the package aimed at building object of S4 class `POSet`
#' (e.g. [POSet()], [LinearPOSet()], [ProductPOSet()], ...) .
#' @param poset2 An object of S4 class `POSet`.
#' Argument `poset2` must be created by using any function contained in the package aimed at building object of S4 class `POSet`
#' (e.g. [POSet()], [LinearPOSet()], [ProductPOSet()], ...) .
#' @param ... Optional additional objects of S4 class `POSet`.
#' Optional arguments must be created by using any function contained in the package aimed at building object of S4 class `POSet`
#' (e.g. [POSet()], [LinearPOSet()], [ProductPOSet()], ...) .
#'
#' @return
#' The intersection poset, an object of S4 class `POSet`.
#'
#' @details
#' Let \eqn{P_1 = (V, \leq_1),\cdots, P_k = (V, \leq_k)} be \eqn{k} posets on the same set \eqn{V}.
#' The intersection poset \eqn{P_{\cap}=P_1 \cap\cdots\cap P_k} is the poset \eqn{(V, \leq_{\cap})} where
#' \eqn{a\leq_{\cap} b} if and only if \eqn{a\leq_i b} for all \eqn{i=1\cdots k}.
#'
#' @examples
#' elems <- c("a", "b", "c", "d")
#'
#' dom1 <- matrix(c(
#'   "a", "b",
#'   "c", "b",
#'   "b", "d"
#' ), ncol = 2, byrow = TRUE)
#'
#' dom2 <- matrix(c(
#'   "a", "b",
#'   "b", "c",
#'   "b", "d"
#' ), ncol = 2, byrow = TRUE)
#'
#' pos1 <- POSet(elements = elems, dom = dom1)
#'
#' pos2 <- POSet(elements = elems, dom = dom2)
#'
#' pos_int <- IntersectionPOSet(pos1, pos2)
#'
#'
#' @name IntersectionPOSet
#' @export IntersectionPOSet
IntersectionPOSet <- function(poset1, poset2, ...) {
  if (!methods::is(poset1, "POSet")) {
    stop("Arguments poset1 must be of class POSet")
  }
  if (!methods::is(poset2, "POSet")) {
    stop("Arguments poset2 must be of class POSet")
  }
  for(p in list(...)) {
    if (!methods::is(p, "POSet")) {
      stop("Additional arguments must be of class POSet")
    }
  }
  posets <- rep(NULL, 2+length(list(...)))
  posets <- c(poset1@ptr)
  posets <- cbind(posets, c(poset2@ptr))
  for(p in list(...)) {
    posets <- cbind(posets, c(p@ptr))
  }
  tryCatch({
    ptr <- .Call("_BuildIntersectionPOSet", posets)
    result <- methods::new("POSet", ptr = ptr)
    return (result)
  }, error = function(err) {
    err_split <- strsplit(err[[1]], split = ":")
    stop(err_split[[1]][length(err_split[[1]])])
  }) # END tryCatch
}
