#' @title
#' Constructing a Partially Ordered Set.
#'
#' @description
#' Constructs an object of class `POSet`, representing a partially ordered set (poset) \eqn{P=(V,\leq)}.
#'
#' @param elements A vector of character strings (the labels of the elements of the ground set \eqn{V}).
#' @param dom Two-columns matrix of element labels, representing the dominances in the order relation
#' \eqn{\leq}. The generic `k-th` row of `dom` contains a pair of elements of \eqn{V}, with
#' `dom[k, 1] `\eqn{ \leq} `dom[k, 2]`.
#'
#' @return
#' An object \eqn{(V, \leq)} of S4 class `POSet`, where \eqn{V} is the ground set and \eqn{\leq} is the partial order relation on it
#'
#' @examples
#' elems <- c("a", "b", "c", "d")
#'
#' dom <- matrix(c(
#'   "a", "b",
#'   "c", "b",
#'   "b", "d"
#' ), ncol = 2, byrow = TRUE)
#'
#' pos <- POSet(elements = elems, dom = dom)
#'
#' @name POSet
#' @export POSet
POSet <- function(elements, dom=matrix(ncol = 2, nrow = 0)) {
  if (!is.character(elements))
    stop("elements must be character array")
  if (length(unique(elements)) != length(elements))
    stop("elements contains duplicated values")
  if (ncol(dom) != 2)
    stop("comp must be two columns character matrix")
  if ((ncol(dom) * nrow(dom) > 0  && !is.character(dom)))
    stop("dom must be two columns character matrix")
  if (!(all(unique(as.vector(dom)) %in% elements)))
    stop("dom contains values not belonging to elements")
  tryCatch({
    ptr <- .Call("_BuildPoset", elements, dom)
    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
}
