# Load default settings for CHNOSZ
reset()

info <- "Unavailable elements cause errors in mass() and entropy()"
# The suppressWarnings here refer to the warnings generated by makeup() about the missing elements
expect_error(suppressWarnings(mass("Xxx")), "element\\(s\\) Xxx not available in thermo\\(\\)\\$element", info = info)
# 20130101: The error below was changed to a warning to restore functionality of check.OBIGT()
#   (species in the database include those with Am Cm Np Pu, not listed in thermo()$element)
expect_warning(entropy("Xxx"), "element\\(s\\) Xxx not available in thermo\\(\\)\\$element", info = info)

info <- "GHS() and ZC() give warnings and errors in some situation"
expect_error(GHS(c("CO2","H2O"), G = 0, H = 0), "formula, G, H and S arguments are not same length", info = info)
expect_error(ZC("H2O"), "carbon not found in the stoichiometric matrix", info = info)
iATP <- info("ATP-4")
expect_warning(ZC(iATP), "element\\(s\\) P .* not included in this calculation", info = info)

info <- "GHS() and OBIGT2eos() produce expected values"
## A species with missing entropy value
ic <- info("cystine")
icdata <- info(ic)
GHS <- GHS(icdata$formula, G = icdata$G, H = icdata$H, S = icdata$S)
expect_equal(GHS[[3]], 61.8102928143, info = info)
# Done through OBIGT2eos
coe <- CHNOSZ:::OBIGT2eos(thermo()$OBIGT[ic,], "aq", fixGHS = TRUE)
expect_equal(coe$S, GHS[[3]], info = info)
## Mass and entropy of elements in chemical formulas
# The "-1" is a single negative charge, the electron
formula <- c("CH4", "H2O", "-1")
calcmass <- mass(formula)
calcS <- convert(entropy(formula), "cal")
expect_equal(calcmass, c(16.04276, 18.01528, 0), info = info)
expect_equal(calcS, c(63.83843212237, 55.74952198853, 15.61663479924), info = info)
# Another way to calculate the entropy of the elements in H2O
calcGHS <- GHS("H2O", G = 0, H = 0, E_units = "cal")
expect_equal(as.numeric(calcGHS[1, 3]), calcS[2], info = info)
  
# Test added on 20260629
# NOTE: detaching the package isn't possible if dependent packages are loaded
CHNOSZ_attached <- "CHNOSZ" %in% (.packages())
if(CHNOSZ_attached) {
  res <- try(detach("package:CHNOSZ", unload = TRUE), silent = TRUE)
  if(!inherits(res, "try-error")) {
    info <- "mass() can process formulas if the package is not attached"
    mH2O <- NULL
    expect_silent(mH2O <- CHNOSZ::mass("H2O"), info = info)
    if(!is.null(mH2O)) expect_equal(mH2O, 18.01528, info = info)
    info <- "entropy() can process formulas if the package is not attached"
    sH2O <- NULL
    expect_silent(sH2O <- CHNOSZ::entropy("H2O"), info = info)
    if(!is.null(sH2O)) expect_equal(sH2O, 233.256, info = info)
    # Reload CHNOSZ so things work normally after this test
    if(CHNOSZ_attached) library(CHNOSZ)
  }
}
