"""Long work: do a long job in small steps with ui.after(0, …), so the window stays responsive.

Callbacks run one at a time on the thread that runs the window, so a callback
that works for seconds freezes it. Instead, each step does a little and
schedules the next with ui.after(0, step): between steps the window draws the
progress and handles taps, so Cancel works mid-job. Keep the step's Timer in
state so Cancel can stop it.
"""

from dataclasses import dataclass, field

from juno import ui

LIMIT = 20_000
STEP = 500


@dataclass
class State:
    checked: int = 0
    primes: list = field(default_factory=list)
    timer: object = None
    result: str = ""


state = State()


def is_prime(number):
    if number < 2:
        return False
    divisor = 2
    while divisor * divisor <= number:
        if number % divisor == 0:
            return False
        divisor += 1
    return True


def step():
    end = min(state.checked + STEP, LIMIT)
    state.primes.extend(n for n in range(state.checked, end) if is_prime(n))
    state.checked = end
    if state.checked < LIMIT:
        state.timer = ui.after(0, step)
    else:
        state.timer = None
        state.result = f"Found {len(state.primes)} primes below {LIMIT}."


def start():
    if state.timer is None:
        state.checked, state.primes, state.result = 0, [], ""
        state.timer = ui.after(0, step)


def cancel():
    if state.timer is not None:
        state.timer.cancel()
        state.timer = None
        state.result = f"Cancelled after {state.checked} numbers."


def body(s):
    working = s.timer is not None
    return ui.VStack(
        ui.Text("Primes", font="title2", weight="bold"),
        ui.ProgressView(value=s.checked / LIMIT, label=f"{s.checked} of {LIMIT} checked"),
        ui.HStack(
            ui.Button("Start", on_press=start, style="filled", busy=working),
            ui.Button("Cancel", on_press=cancel, style="bordered", disabled=not working),
            spacing=12),
        ui.Text(s.result),
        padding=16, spacing=16, width="fill", max_width=680)


if __name__ == "__main__":
    ui.run(body, state, title="Long work")
