import pandas as pd
import numpy as np

from jinja2 import Template

from bokeh.io import output_file, show, vform
from bokeh.plotting import *
from bokeh.charts import *
from bokeh.models import *
from bokeh.models.widgets import CheckboxButtonGroup
from bokeh.embed import components
from bokeh.resources import INLINE
from bokeh.util.browser import view

###### -- Difined color palette-- ########
Fblue = "#3fa0d4"
Fdark_green = "#47994b"
Flight_green = "#88ba14"
Fgrey_blue = "#437c92"
Fturquoise ="#0aaba4"
Fsand ="#dabe86"
Fbrown ="#59392a"
Fred ="#C90119"
Fsand20 ="#f7f2e7"
###### -- end -- ########


########## DATA ################

###### -- Import -- ########
with pd.ExcelFile('Example.xlsx') as xlsx:
    df1 = pd.read_excel(xlsx, 'Day')
    df2 = pd.read_excel(xlsx, 'Night')
###### -- end -- ########

###### -- Create Column Data Source that will be used by the plot -- ########
data = dict(Pressure=df1["Pressure"],
            Depth=df1["Depth"],
            Temperature=df1["Temperature"],
            Salinity=df1["Salinity"],
            Conductivity=df1["Conductivity"],
            Density=df1["Density"],
            DescentRate=df1["Descent Rate"],
            SoundVelocity=df1["Sound Velocity"],
            Oxygenraw=df1["Oxygen raw"],
            Oxygenmgl=df1["Oxygen [mg/l]"],
            Oxygenpercent=df1["Oxygen [%]"],
            Flag=df1["Flag"]
            )
source = ColumnDataSource(data)
###### -- end -- ########



###### -- TODO: Night -- ########
data2 = dict(Pressure=df2["Pressure"],
            Depth=df2["Depth"],
            Temperature=df2["Temperature"],
            Salinity=df2["Salinity"],
            Conductivity=df2["Conductivity"],
            Density=df2["Density"],
            DescentRate=df2["Descent Rate"],
            SoundVelocity=df2["Sound Velocity"],
            Oxygenraw=df2["Oxygen raw"],
            Oxygenmgl=df2["Oxygen [mg/l]"],
            Oxygenpercent=df2["Oxygen [%]"],
            Flag=df2["Flag"]
            )
source2 = ColumnDataSource(data2)
###### -- end -- ########



################ PLOTS PARAMETERS ################
###### -- Main-- ########
TOOLS = 'crosshair,pan,wheel_zoom,box_zoom,reset,hover,save'
plot_options = dict(y_axis_label="Depth [m]", background_fill_color=Fsand20, width=450, height=450, title=None, tools=TOOLS)
###### -- end -- ########

###### -- Set up Ratio button to show/hide cast -- ########
#callback = CustomJS(args=dict(source=source), code="""
#        // get data source from Callback args
#        var data = source.get('data');
#        var value = cb_obj.get('value')
#
#        /// update data source with new attribute
#        if (value == "Both") { return; }
#
#        for (i = 0; i < data['Flag'].length; ++i) {
#            data['Flag'][i] == cast);
#        }

#        // trigger update of data source
#        source.trigger('change');
#    """)

callback = CustomJS(args=dict(source=source), code="""
        // get data source from Callback args
        var plot_data = source.get('data');
        var original_data = original_source.get('data');
        var cast = cb_obj.get('value');

        /// update data source with new attribute
        if (cast == 'Both') { return; };

        else if (cast == 'Downcast') {
            plot_data.filter(data['Flag'], cast);
            //source = df1.loc[df1['Flag'] == "Downcast"];
        };

        // trigger update of data source
        source.trigger('change');
    """)


cast_select = Select(value='Both', title='Cast', options=['Both', 'Downcast', 'Upcast'], callback=callback)

b = vform(cast_select)

#depth_select = TextInput(title="Depth [m]")
#s = vform(depth_select)
###### -- end -- ########


########## PLOTS ################

###### -- First one -- ########
line0 = figure(**plot_options)
line0.line('Temperature', 'Depth', source=source, color=Fred)
line0.xaxis.axis_label = "Temperature [°C]"
line0.y_range.bounds = 'auto'
line0.axis.axis_label_text_font_size = "14pt"
line0.axis.axis_label_text_font_style = "bold"
###### -- end -- ########

###### -- linked panning is expressed by sharing ranges between plots.  -- ########
line1 = figure(y_range=line0.y_range, **plot_options)
line1.line('Salinity', 'Depth', source=source, color=Fblue)
line1.xaxis.axis_label = "Salinity [PSU]"
line1.axis.axis_label_text_font_size = "14pt"
line1.axis.axis_label_text_font_style = "bold"

line2 = figure(y_range=line0.y_range, **plot_options)
line2.line('Conductivity', 'Depth', source=source, color=Fturquoise)
line2.xaxis.axis_label = "Conductivity [S/m]"
line2.axis.axis_label_text_font_size = "14pt"
line2.axis.axis_label_text_font_style = "bold"

line3 = figure(y_range=line0.y_range, **plot_options)
line3.line('Density', 'Depth', source=source, color=Fbrown)
line3.xaxis.axis_label = "Density [kg/m^3]"
line3.axis.axis_label_text_font_size = "14pt"
line3.axis.axis_label_text_font_style = "bold"

line4 = figure(y_range=line0.y_range, **plot_options)
line4.line('SoundVelocity', 'Depth', source=source, color=Fgrey_blue)
line4.xaxis.axis_label = "Sound Velocity [Delgrosso, m/s]"
line4.axis.axis_label_text_font_size = "14pt"
line4.axis.axis_label_text_font_style = "bold"

line5 = figure(y_range=line0.y_range, **plot_options)
line5.line('Oxygenmgl', 'Depth', source=source, color=Fdark_green)
line5.xaxis.axis_label = "Dissolved Oxygen [mg/l]"
line5.axis.axis_label_text_font_size = "14pt"
line5.axis.axis_label_text_font_style = "bold"

line6 = figure(y_range=line0.y_range, **plot_options)
line6.line('Oxygenpercent', 'Depth', source=source, color=Flight_green)
line6.xaxis.axis_label = "Dissolved Oxygen [% saturation]"
line6.axis.axis_label_text_font_size = "14pt"
line6.axis.axis_label_text_font_style = "bold"
###### -- end -- ########

###### -- Grid plot option -- ########
p = gridplot([[line0, line1, line3, line5],
             [line2, None, line4, line6]]
        )
###### -- end -- ########

###### -- Hover tool option -- ########
hover = p.select(dict(type=HoverTool))
hover.mode = 'mouse'
hover.tooltips = [
    ("Depth", "$y{1.1}"), # this will format as 1-decimal float
    ("Measure", "$x{1.1}") # this will format as 1-decimal float
]
###### -- end -- ########

########## RENDER PLOTS ################
###### -- Define our html template for out plots -- ########
template = Template('''<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
	<title>Station E04 - SeaBird data</title>
        {{ js_resources }}
        {{ css_resources }}
    </head>
    <body>
    <h2>Test</h2>
    <h3>Data</h3>
    <h4>Filters</h4>
    {{ plot_div.b }}
    <h4>Plots</h4>
    {{ plot_div.p }}

    {{ plot_script }}
    </body>
</html>
''')

resources = INLINE

js_resources = resources.render_js()
css_resources = resources.render_css()

script, div = components({'b': b, 'p': p})

html = template.render(js_resources=js_resources,
                       css_resources=css_resources,
                       plot_script=script,
                       plot_div=div)
###### -- end -- ########

###### -- save the document in a HTML -- ########
filename = 'embed_multiple_responsive.html'

with open(filename, 'w') as f:
    f.write(html)
###### -- end -- ########

###### -- open the document in a browser -- ########
view(filename)

################ END OF SCRIPT ################
