"""
example derived from:
https://bokeh.pydata.org/en/latest/docs/user_guide/annotations.html#box-annotations
"""

from bokeh.plotting import figure, curdoc
from bokeh.layouts import row, column
from bokeh.plotting import output_file
from bokeh.models import BoxAnnotation
from bokeh.models.widgets import Button


# In[0]:
def draw_plot3():
    TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
    
    x = [0,1,2,3]
    y = [-10,220,40,90]
    
    p = figure(x_axis_type="datetime", tools=TOOLS)
    
    p.line(x=x, y=y, line_color="gray", line_width=1)
    
    p.title.text = "Glucose Range"
    p.xgrid[0].grid_line_color=None
    p.ygrid[0].grid_line_alpha=0.5
    p.xaxis.axis_label = 'Time'
    p.yaxis.axis_label = 'Value'
    
    return p


# In[0]
# times_df: columns=('start','stop') which are the start and stop times to draw
#           the box annotations.  These need to be pre-processed to the correct
#           padding since this add_box_annotations() function just adds them
#           to the figure.
# https://bokeh.pydata.org/en/latest/docs/user_guide/annotations.html
# COUPLING with clear_box_annotations() in the name of the box annotation
def add_box_annotations(f,fill_alpha=0.1,fill_color='red'):
    import pandas as pd
    
    print(">>>add_box_annotations")

    start = pd.Series([0.1,1.2,2.5])
    stop  = pd.Series([0.3,1.5,2.9])
    df = pd.DataFrame(columns=['start','stop'])
    df.loc[:,'start'] = start
    df.loc[:,'stop'] = stop
    #times_df

    # i is the index
    # r is the row
    for i, r in df.iterrows():
        #print(r.start)
        #print(r.stop)
        left = r.start
        right = r.stop
        box = BoxAnnotation(name='my_box_annotation',left=left,right=right, fill_alpha=fill_alpha, fill_color=fill_color)
        
        f.add_layout(box)    

    for i,r in enumerate(f.renderers):
        if r.name == 'my_box_annotation':
            print("   found my_box_annotation after adding annotations")
    print("<<<add_box_annotations")

# TODO:
#   coupling with the glyph removal code... harmonize... and pass in something
#   to identify what needs to be removed.
# COUPLING with add_box_annotations() in the name of the box annotation
def clear_box_annotations(f):
    print(">>>clear_box_annotations")
    f.renderers = [r for r in f.renderers if r.name != 'my_box_annotation'] 
    print("<<<clear_box_annotations")


# In[0]:
#=======================
# Buttons and call-backs
#-----------------------
def print_note_if_my_box_annotation_found(f,some_str):
    for i,r in enumerate(f.renderers):
        print(str(type(r)))
        if r.name == 'my_box_annotation':
            print(str(some_str))
    
    
def add_box_annotations_handler():
    print(">>>add_box_annotations_handler")

    print_note_if_my_box_annotation_found(f,"found my_box_annotation prior to adding more")

    add_box_annotations(f)

    print_note_if_my_box_annotation_found(f,"found my_box_annotation after adding more")

    print("<<<add_box_annotations_handler")

def clear_box_annotations_handler():
    print(">>>clear_box_annotations_handler")

    print_note_if_my_box_annotation_found(f,"found my_box_annotation before removing annotations")

    clear_box_annotations(f)
    
    print_note_if_my_box_annotation_found(f,"found my_box_annotation after removing annotations")

    print("<<<clear_box_annotations_handler")
        
def add_delete_box_annotations_handler():
    print(">>>add_delete_box_annotations_handler")

    # Add Annotations
    print_note_if_my_box_annotation_found(f,"found my_box_annotation before adding annotations")
    add_box_annotations(f)
    print_note_if_my_box_annotation_found(f,"found my_box_annotation after adding annotations")

    # Clear Annotations
    clear_box_annotations(f)
    print_note_if_my_box_annotation_found(f,"found my_box_annotation after removing annotations")

    print("<<<add_delete_box_annotations_handler")
    

add_button = Button(label='add', width=150)
delete_button = Button(label='delete', width=150)
add_delete_button = Button(label='add then delete', width=150)
add_button.on_click(add_box_annotations_handler)
delete_button.on_click(clear_box_annotations_handler)
add_delete_button.on_click(add_delete_box_annotations_handler)

# In[0]
#======================
# initialize the layout
f = draw_plot3()

# Debug 1:
# uncommenting the following results in the expected behavior of box annotations
# being added to the plot when the plot is first displayed to the user.
#add_box_annotations(f)

# Debug 2:
# uncommenting the previous along with following results in the expected behavior
# of the box annotations being removed prior to the plot being displayed to the
# user for the first time.
#clear_box_annotations(f)

# Debug 3:
# clicking on the "add" button results in the expected behavior of box annotations
# being added.

# Debug 4:
# clicking on the "delete" button (with an annotation displayed) results in the
# unexpected behavior of nothing getting deleted.

# In[0]

c = column(f,add_button,delete_button,add_delete_button)
curdoc().add_root(c)
curdoc().title = 'Layout Buttons'
