import pandas as pd
from bokeh.plotting import figure, show, output_notebook

# Get data
df = pd.read_csv('data/Land_Ocean_Monthly_Anomaly_Average.csv')

# Process data
df['datetime'] = pd.to_datetime(df['datetime'])
df = df[['anomaly','datetime']]
df['moving_average'] = pd.rolling_mean(df['anomaly'], 12)

# Output option
output_notebook()

# Create your plot
p = figure()
p.line(df['datetime'], df['anomaly'])
p.line(df['datetime'], df['moving_average'])

# Show plot
show(p)

"""
Explanation: <img src=images/continuum_analytics_b&w.png align="left" width="15%" style="margin-right:15%">
<h1 align='center'>Bokeh tutorial</h1>

1.2 Plotting - Timeseries
Exercise: Reproduce the timeseries chart using the plotting interface

Data: 'data/Land_Ocean_Monthly_Anomaly_Average.csv'

Note: Don't worry about styling right now. We'll go over plot properties in the next exercise
End of explanation
"""


from bokeh.models import DatetimeTickFormatter
import math

# Axis type, width and height
t = figure(x_axis_type = "datetime", width=900, height=200)

# Line colors and legend 
t.line(df['datetime'], df['anomaly'], color='lightgrey', legend='anom')
t.line(df['datetime'], df['moving_average'], color='red', legend='avg')

# Axis format (e.g tick format and orientation)
xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"]))
t.xaxis[0].formatter = xformatter
t.xaxis.major_label_orientation = math.pi/4

# Axis labels
t.yaxis.axis_label = 'Anomaly(ºC)'

# Legend position
t.legend.location = "bottom_right"

# Grid style
t.grid.grid_line_alpha=0.2

# Remove toolbar
t.toolbar_location=None

# Show plot
show(t)

"""
Explanation: Exercise: Style the plot appropriately
Ideas:

Axis type and format
Line colors
Legend
Grid lines
Axis labels
Width and height
Remove toolbar

Tips:
bokeh.models.DatetimeTickFormatter()

Note: You can create a new figure to see observe the differences.
End of explanation
"""


from bokeh.models import ColumnDataSource, HoverTool
from collections import OrderedDict

# List all the tools that you want in your plot separated by comas, all in one string.
TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave"

# Add the tools to your figure
t = figure(x_axis_type = "datetime", width=1000, height=200,tools=TOOLS)

# The hover tools doesn't render datetime appropriately. We'll need a string.
df["datetime_s"]=df[["datetime"]].applymap(str)

# To reference variables in the hover box, we'll need to use bokeh.ColumnDataSource instead of a pd.DataFrame
source = ColumnDataSource(df)

# Change plotting.line to get values from ColumnDataSource, name the renderer that you want to have the hover activated
t.line('datetime', 'anomaly', color='lightgrey', legend='anom', source=source)
t.line('datetime', 'moving_average', color='red', legend='avg', source=source, name="mva")

# Set hover tool
hover = t.select(dict(type=HoverTool))
hover.tooltips = OrderedDict([
    ("anomaly", "@anomaly"),
    ("datetime", "@datetime_s"),
])
hover.renderers = t.select("mva")

# Copy your style from the previous exercise
xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"]))
t.xaxis[0].formatter = xformatter
t.xaxis.major_label_orientation = math.pi/4
t.yaxis.axis_label = 'Anomaly(ºC)'
t.legend.location = "bottom_right"
t.grid.grid_line_alpha=0.2
t.toolbar_location=None

# Show plot
show(t)

"""
Explanation: Exercise: Add a crosshair and hover tool to the plot
End of explanation
"""


# New figure
t = figure(x_axis_type = "datetime", width=1000, height=200,tools=TOOLS)

# Data processing
# The hover tools doesn't render datetime appropriately. We'll need a string. 
# We just want dates, remove time
f = lambda x: str(x)[:7]
df["datetime_s"]=df[["datetime"]].applymap(f)
source = ColumnDataSource(df)

# Create plot
t.line('datetime', 'anomaly', color='lightgrey', legend='anom', source=source)
t.line('datetime', 'moving_average', color='red', legend='avg', source=source, name="mva")

# Style
xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"]))
t.xaxis[0].formatter = xformatter
t.xaxis.major_label_orientation = math.pi/4
t.yaxis.axis_label = 'Anomaly(ºC)'
t.legend.location = "bottom_right"
t.grid.grid_line_alpha=0.2
t.toolbar_location=None

# Style hover tool
hover = t.select(dict(type=HoverTool))
hover.tooltips = """
    <div>
        <span style="font-size: 15px;">Anomaly</span>
        <span style="font-size: 17px;  color: red;">@anomaly</span>
    </div>
    <div>
        <span style="font-size: 15px;">Month</span>
        <span style="font-size: 10px; color: grey;">@datetime_s</span>
    </div>
    """
hover.renderers = t.select("mva")

# Show plot
show(t)

"""
Explanation: [OPTIONAL] Exercise: Style the hover tooltip 
http://bokeh.pydata.org/en/latest/docs/user_guide/tools.html#custom-tooltip
End of explanation
"""


