# ============================================================
#  main.py — de Python-code van de voorbeeldsite
# ============================================================

from pyscript import web, when


# ------------------------------------------------------------
#  1. FACULTEIT  —  één invoerveld
# ------------------------------------------------------------

def faculteit(n):
    uitkomst = 1
    for getal in range(1, n + 1):
        uitkomst = uitkomst * getal
    return uitkomst


@when("click", "#knop-faculteit")
def knop_faculteit(event):
    n = int(web.page["invoer-faculteit"].value)
    web.page["uitvoer-faculteit"].innerText = str(n) + "! = " + str(faculteit(n))


# ------------------------------------------------------------
#  2. PYTHAGORAS  —  twee invoervelden
# ------------------------------------------------------------

def wortel(x):
    if x == 0:
        return 0
    gok = x / 2
    for i in range(20):
        gok = (gok + x / gok) / 2
    return gok


def schuine_zijde(a, b):
    return wortel(a * a + b * b)


@when("click", "#knop-pythagoras")
def knop_pythagoras(event):
    a = float(web.page["invoer-a"].value)
    b = float(web.page["invoer-b"].value)
    web.page["uitvoer-pythagoras"].innerText = "c = " + str(round(schuine_zijde(a, b), 4))


# ------------------------------------------------------------
#  3. VALUTA  —  één invoerveld, vijf uitvoerplekken
# ------------------------------------------------------------

# id van het uitvoerveld -> (koers, teken)   — vaste voorbeeldkoersen
KOERSEN = {
    "uit-usd": (1.09, "$"),
    "uit-gbp": (0.85, "£"),
    "uit-jpy": (172.0, "¥"),
    "uit-chf": (0.94, "CHF"),
    "uit-sar": (4.09, "SAR"),
}


def omrekenen(euro, koers):
    return euro * koers


@when("click", "#knop-valuta")
def knop_valuta(event):
    euro = float(web.page["invoer-euro"].value)
    for veld_id in KOERSEN:
        koers, teken = KOERSEN[veld_id]
        bedrag = omrekenen(euro, koers)
        web.page[veld_id].innerText = teken + " " + f"{bedrag:.2f}"   # altijd 2 decimalen
