# -*- coding: utf-8 -*-
"""
Demonstrate the odd transition when updating a figure using
Plotly in Solara.
Created: 11 September 2024
Revised:
"""
import solara
import plotly.graph_objects as pgo
from scipy.signal import sweep_poly
from numpy import linspace, poly1d
DARK_SAGE = "#8da375"
LIGHT_GRAY = "#bbbbbb"
plotly_figure = solara.Reactive(pgo.Figure)
def get_figure(xrange: list | None = None) -> pgo.Figure:
    """ Build the basic figure and common layout (minus the data) """
    empty_fig = pgo.Figure()
    empty_fig.update_layout(paper_bgcolor=LIGHT_GRAY,
                            showlegend=False,
                            legend={"borderwidth": 1,
                                    "bordercolor": "black"},
                            hovermode="closest")
    empty_fig.update_xaxes(title_text="Time", gridcolor="gray",
                           range=xrange, ticks="outside")
    empty_fig.update_yaxes(title_text="Amplitude", gridcolor="gray",
                           ticks="outside")
    return empty_fig
def add_figure_data(p_fig: pgo.Figure, data: dict) -> pgo.Figure:
    """ Add a data trace to the prepared figure """
    marker = {"color": data["color"],
              "size": 3,
              "symbol": "circle"}
    trace_x = pgo.Scatter(x=data["time"], y=data["amplitude"],
                          marker=marker, mode="markers",
                          line={"width": 0})
    p_fig.add_trace(trace_x)
    return p_fig
# ============================================================================
def get_data(samples: int, xper: int, subsample: int,
             offset: int, color: str) -> dict:
    """ Build a dataset """
    data = dict(time=linspace(0, samples-1, samples).astype(int),
                amplitude=(sweep_poly(linspace(0, subsample, samples),
                                      poly1d(1), 45) * xper) + offset,
                color=color)
    return data
data_1 = get_data(7057, 29, 19, 353, "green")
data_2 = get_data(2311,  61, 11, 241, "blue")
# ============================================================================
def button_handler1():
    fig = get_figure(xrange=[data_1["time"][0], data_1["time"][-1]])
    add_figure_data(fig, data_1)
    fig.update_layout(title="Plot 1")
    plotly_figure.value = fig
def button_handler2():
    fig = get_figure(xrange=[data_2["time"][0], data_2["time"][-1]])
    add_figure_data(fig, data_2)
    fig.update_layout(title="Plot 2")
    plotly_figure.value = fig
@solara.component
def Page():
    solara.use_memo(button_handler1)
    with solara.Card(title="Solara-Plotly Transition Example",
                     elevation=3,
                     style={'background-color': DARK_SAGE,
                            'width': '900px'}):
        with solara.Column(gap='20px',
                           style={'background-color': DARK_SAGE}):
            solara.FigurePlotly(plotly_figure.value,
                                dependencies=[plotly_figure.value['data']])
            with solara.Row(margin=2,
                            style={"background-color": LIGHT_GRAY,
                                   "padding": "5px"}):
                solara.Button("Plot 1", on_click=button_handler1)
                solara.Button("Plot 2", on_click=button_handler2)