import dash_pdf_highlighter
import dash
from dash import dcc, html, callback, Input, Output, State
import json
import datetime
import random

app = dash.Dash(__name__)



app.layout = html.Div(
    style={"display": "flex", "padding": "0", "margin": "0", "height": "100vh"},
    children=[
        dash_pdf_highlighter.PdfViewer(
            id="pdf-viewer",
            url="https://arxiv.org/pdf/1104.4284",
            style={"width": "70vw", "height": "100vh"},
            highlights=[]
        ),
        html.Div(
            [
                dcc.Input(id="url-input", type="text", value="https://arxiv.org/pdf/1104.4284"),
                html.Button(["update url"], id="update-url"),
                html.Br(),

                html.Button(["calc highlights"], id="update-highlight"),
                dcc.Input(id="highlight-idx", type="number", value=0),
                html.Div(id="output"),
                dcc.Store(id="store"),
            ],
            
            style={"backgroundColor": "gray", "width": "30vw", "height": "100vh", "overflowY": "scroll"},
        )
    ],
)


@callback(Output("output", "children"), Input("pdf-viewer", "highlights"))
def update_output(highlights):
    
    if highlights and "content" in highlights[0] and "text" in highlights[0]["content"]:
        output = [ dcc.Markdown(
            highlights[0]["content"]["text"]
            )]
        if "image" in highlights[0]["content"]:
            output = [html.Img(src=highlights[0]["content"]["image"], style={"width": "100%"})] + output

        return output
    else:
        return html.Pre(json.dumps(highlights, indent=2))



@callback(
    Output("store", "data"),
    Output("highlight-idx", "value"),
    Input("update-highlight", "n_clicks"),
    State("pdf-viewer", "url"),
    prevent_initial_call=True
)
def load_highlights(n_clicks, url):

    segmenter = dash_pdf_highlighter.Segmenter(debug=True)

    highlights = segmenter.run(url)

    return highlights, 0

@callback(
    Output("pdf-viewer", "highlights"),
    Input("highlight-idx", "value"),
    State("store", "data"),
    prevent_initial_call=True
)
def update_highlight(idx, stored_highlights):
    if stored_highlights and 0 <= idx < len(stored_highlights):
        return [stored_highlights[idx]]
    return []


@callback(
    Output("pdf-viewer", "url"),
    Input('update-url', "n_clicks"),
    State("url-input", "value"),
    prevent_initial_call=True
)
def update_url(_, new_url):
    return new_url


if __name__ == "__main__":
    app.run_server(debug=True)
