import numpy as np
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import render_widget

from sparkline_widget import Sparkline

ui.page_opts(title="anywidget: custom messages both ways", fillable=True)
ui.input_action_button("flash", "Flash the line (Python -> JS message)")
ui.markdown("Double-click the line to send a message the other way (JS -> Python).")

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card():

        @render_widget
        def spark():
            rng = np.random.default_rng(2)
            return Sparkline(values=list(rng.normal(size=40).cumsum()))

        # Python -> JS, a custom message: `widget.send(...)` arrives in JS as
        # a "msg:custom" event (see sparkline_widget.py). Even sent before
        # the widget's comm is fully open -- from inside the render function
        # itself, or an effect with no dependency -- it's queued and
        # delivered once the comm opens, so nothing is lost.
        @reactive.effect
        @reactive.event(input.flash)
        def _flash():
            spark.widget.send({"type": "flash"})

    with ui.card():
        ui.card_header("Messages received from the widget")

        reset_count = reactive.value(0)

        @reactive.effect
        def _wire_on_msg():
            def _on_msg(widget, content, buffers):
                if content.get("type") == "reset-requested":
                    reset_count.set(reset_count() + 1)

            spark.widget.on_msg(_on_msg)

        @render.code
        def resets_out():
            idx = spark.read("clicked_index")
            return (
                f"clicks so far (via trait): {idx}\n"
                f"double-click messages received: {reset_count()}"
            )
