// Chemistry homework as a service: formulas read, molar masses, percent composition, equations
// balanced, a limiting reagent, and the table of elements.
//
//   quillo run chemistry.qwe
//   then open http://localhost:8080/formula?f=Fe2(SO4)3, /balance?eq=C3H8+%2B+O2+-%3E+CO2+%2B+H2O and /examples

use "chemistry.qwer"

route GET /formula ? { f: str } {
    let r = chem_parse(f)
    if is_err(r) { reply 422 r.error }
    { read: r, composition: chem_composition(f)? }
}

route GET /balance ? { eq: str } {
    let r = chem_balance(eq)
    if is_err(r) { reply 422 r.error }
    r
}

route GET /examples = {
    water: chem_molar_mass("H2O")?,
    sulfate: chem_molar_mass("Fe2(SO4)3")?,
    hydrate: chem_parse("CuSO4·5H2O")?.atoms,
    complex: chem_parse("K4[Fe(CN)6]")?.hill,
    ion: chem_parse("SO4^2-")?.charge,
    glucose: chem_composition("C6H12O6")?,
    moles: chem_moles("H2O", 36.03)?,
    vinegar: chem_empirical({ C: 40.0, H: 6.71, O: 53.29 })?,
    rust: chem_empirical({ Fe: 69.94, O: 30.06 })?,
}

route GET /equations = {
    combustion: chem_balance("C3H8 + O2 -> CO2 + H2O")?.equation,
    states: chem_balance("Al(s) + HCl(aq) -> AlCl3(aq) + H2(g)")?.equation,
    redox: chem_balance("KMnO4 + HCl -> KCl + MnCl2 + H2O + Cl2")?.coefficients,
    ionic: chem_balance("MnO4^- + Fe^2+ + H^+ -> Mn^2+ + Fe^3+ + H2O")?.coefficients,
    limiting: chem_limiting("H2 + O2 -> H2O", { H2: 4.0, O2: 16.0 })?,
    one_side: chem_balance("H2 + O2 -> NaCl").error,
    two_ways: chem_balance("H2 + O2 + CO -> H2O + CO2").error,
    no_arrow: chem_balance("H2 + O2").error,
}

route GET /elements = {
    gold: chem_element("Au")?,
    by_number: chem_element(26)?.name,
    by_name: chem_element("sodium")?.symbol,
    american: chem_element("aluminum")?.symbol,
    count: len(chem_elements()),
    last: last(chem_elements()).name,
}

route GET /refused = {
    element: chem_parse("Xx2O").error,
    bracket: chem_parse("Fe2(SO4").error,
    nothing: chem_parse("  ").error,
    unknown: chem_element("kryptonite").error,
}
