import tkinter as tk


def get_value(entry):
    """Vrátí číslo z textboxu nebo None, pokud je prázdný."""
    text = entry.get().strip().replace(",", ".")

    if text == "":
        return None

    return float(text)


def set_value(entry, value):
    """Zapíše číslo do textboxu bez zbytečných nul."""
    entry.delete(0, tk.END)

    text = f"{value:.4f}".rstrip("0").rstrip(".")
    entry.insert(0, text)


def calculate():
    try:
        c1 = get_value(entry_c1)
        v1 = get_value(entry_v1)
        c2 = get_value(entry_c2)
        v2 = get_value(entry_v2)

        aroma = get_value(entry_aroma)

        # Prázdné aroma znamená 0 ml
        if aroma is None:
            aroma = 0

        # Zjistíme počet prázdných polí mezi C1, V1, C2, V2
        values = [c1, v1, c2, v2]

        if values.count(None) != 1:
            label_result.config(
                text="Musíš vyplnit právě 3 hodnoty z C₁, V₁, C₂ a V₂."
            )
            return

        # ------------------------------------------
        # Výpočet chybějící hodnoty
        # ------------------------------------------

        # C1
        if c1 is None:
            if v1 == 0:
                label_result.config(
                    text="V₁ nesmí být nula."
                )
                return

            c1 = (c2 * v2) / v1
            set_value(entry_c1, c1)

        # V1
        elif v1 is None:
            if c1 == 0:
                label_result.config(
                    text="C₁ nesmí být nula."
                )
                return

            v1 = (c2 * v2) / c1
            set_value(entry_v1, v1)

        # C2
        elif c2 is None:
            if v2 == 0:
                label_result.config(
                    text="V₂ nesmí být nula."
                )
                return

            c2 = (c1 * v1) / v2
            set_value(entry_c2, c2)

        # V2
        elif v2 is None:
            if c2 == 0:
                label_result.config(
                    text="C₂ nesmí být nula."
                )
                return

            v2 = (c1 * v1) / c2
            set_value(entry_v2, v2)

        # ------------------------------------------
        # Výpočet množství PG/VG báze
        # ------------------------------------------

        base = v2 - v1 - aroma

        if base < 0:
            label_result.config(
                text=(
                    "Výpočet proběhl, ale výsledný objem je neplatný.\n\n"
                    f"Nikotinová báze / booster: {v1:.2f} ml\n"
                    f"Aroma: {aroma:.2f} ml\n"
                    f"Celkový objem: {v2:.2f} ml\n\n"
                    "Součet boosteru a aroma je větší než celkový objem."
                )
            )
            return

        # ------------------------------------------
        # Výsledek
        # ------------------------------------------

        label_result.config(
            text=(
                "Výsledek:\n\n"
                f"Nikotinová báze / booster: {v1:.2f} ml\n"
                f"Aroma: {aroma:.2f} ml\n"
                f"PG/VG báze: {base:.2f} ml\n"
                f"------------------------------\n"
                f"Celkový objem: {v2:.2f} ml\n"
                f"Cílová koncentrace: {c2:.2f} mg/ml"
            )
        )

    except ValueError:
        label_result.config(
            text="Zadej platná čísla. Můžeš použít tečku i čárku."
        )


def clear_fields():
    """Vymaže všechna vstupní pole."""

    for entry in (
        entry_c1,
        entry_v1,
        entry_c2,
        entry_v2,
        entry_aroma
    ):
        entry.delete(0, tk.END)

    label_result.config(
        text="Vyplň 3 hodnoty z C₁, V₁, C₂ a V₂.\n"
             "Aroma je volitelné."
    )


# ==================================================
# GUI
# ==================================================

root = tk.Tk()
root.title("Nikotin kalkulačka")
root.resizable(False, False)

main_frame = tk.Frame(root, padx=15, pady=15)
main_frame.pack()


# --------------------------------------------------
# C1
# --------------------------------------------------

tk.Label(
    main_frame,
    text="C₁ (mg/ml)"
).grid(
    row=0,
    column=0,
    sticky="w",
    pady=4
)

entry_c1 = tk.Entry(main_frame, width=15)
entry_c1.grid(
    row=0,
    column=1,
    padx=10
)

tk.Label(
    main_frame,
    text="= koncentrace nikotinové báze, kterou máš"
).grid(
    row=0,
    column=2,
    sticky="w"
)


# --------------------------------------------------
# V1
# --------------------------------------------------

tk.Label(
    main_frame,
    text="V₁ (ml)"
).grid(
    row=1,
    column=0,
    sticky="w",
    pady=4
)

entry_v1 = tk.Entry(main_frame, width=15)
entry_v1.grid(
    row=1,
    column=1,
    padx=10
)

tk.Label(
    main_frame,
    text="= objem této báze / boosteru"
).grid(
    row=1,
    column=2,
    sticky="w"
)


# --------------------------------------------------
# C2
# --------------------------------------------------

tk.Label(
    main_frame,
    text="C₂ (mg/ml)"
).grid(
    row=2,
    column=0,
    sticky="w",
    pady=4
)

entry_c2 = tk.Entry(main_frame, width=15)
entry_c2.grid(
    row=2,
    column=1,
    padx=10
)

tk.Label(
    main_frame,
    text="= cílová koncentrace liquidu"
).grid(
    row=2,
    column=2,
    sticky="w"
)


# --------------------------------------------------
# V2
# --------------------------------------------------

tk.Label(
    main_frame,
    text="V₂ (ml)"
).grid(
    row=3,
    column=0,
    sticky="w",
    pady=4
)

entry_v2 = tk.Entry(main_frame, width=15)
entry_v2.grid(
    row=3,
    column=1,
    padx=10
)

tk.Label(
    main_frame,
    text="= celkový objem hotového liquidu"
).grid(
    row=3,
    column=2,
    sticky="w"
)


# --------------------------------------------------
# Aroma
# --------------------------------------------------

tk.Label(
    main_frame,
    text="Aroma (ml)"
).grid(
    row=4,
    column=0,
    sticky="w",
    pady=4
)

entry_aroma = tk.Entry(main_frame, width=15)
entry_aroma.grid(
    row=4,
    column=1,
    padx=10
)

tk.Label(
    main_frame,
    text="= množství přidaného aroma"
).grid(
    row=4,
    column=2,
    sticky="w"
)


# --------------------------------------------------
# Tlačítka
# --------------------------------------------------

button_frame = tk.Frame(main_frame)
button_frame.grid(
    row=5,
    column=0,
    columnspan=3,
    pady=15
)

btn_calculate = tk.Button(
    button_frame,
    text="Vypočítej",
    width=15,
    command=calculate
)

btn_calculate.grid(
    row=0,
    column=0,
    padx=5
)

btn_clear = tk.Button(
    button_frame,
    text="Vyčistit",
    width=15,
    command=clear_fields
)

btn_clear.grid(
    row=0,
    column=1,
    padx=5
)


# --------------------------------------------------
# Výsledek
# --------------------------------------------------

label_result = tk.Label(
    main_frame,
    text=(
        "Vyplň 3 hodnoty z C₁, V₁, C₂ a V₂.\n"
        "Aroma je volitelné."
    ),
    justify="left",
    anchor="w",
    font=("Arial", 10)
)

label_result.grid(
    row=6,
    column=0,
    columnspan=3,
    sticky="w",
    pady=(5, 0)
)


root.mainloop()