import numpy as np

from bokeh.io import curdoc
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, Slider, TextInput
from bokeh.plotting import figure

# Set up data

import navani.echem as ec

df = ec.echem_file_loader('data/bs542_004_gr_li_50ua_50mv_1v_191020_Channel_11 copy.xlsx')

mask = df['full cycle'] == 1
half_cycles = df[mask]['half cycle'].unique()
x = df[mask]['Capacity']
y = df[mask]['Voltage']

xs = []
ys = []

for half_cycle in half_cycles:
    mask = df['half cycle'] == half_cycle
    x = df[mask]['Capacity']
    y = df[mask]['Voltage']
    xs.append(x)
    ys.append(y)

source = ColumnDataSource(data=dict(xs=xs, ys=ys))

# Set up plot
plot = figure(plot_height=400, plot_width=400, title="Charge Discharge plot",
                tools="crosshair,pan,reset,save,wheel_zoom,box_zoom",
                x_range=[min(x), max(x)], y_range=[min(y), max(y)])

plot.multi_line('xs', 'ys', source=source, line_width=3, line_alpha=0.6)

# Set up widgets
text = TextInput(title="title", value='My cycle plot')
cycle = Slider(title='Cycle', value=1, start=-df['full cycle'].min(), end=df['full cycle'].max(), step=1)

# Set up callbacks
def update_title(attrname, old, new):
    plot.title.text = text.value

text.on_change('value', update_title)

def update_data(attrname, old, new):

    # Get the current slider values
    cycle_number = cycle.value

    # Generate the new curve
    mask = df['full cycle'] == cycle_number
    half_cycles = df[mask]['half cycle'].unique()
    x = df[mask]['Capacity']
    y = df[mask]['Voltage']

    xs = []
    ys = []

    for half_cycle in half_cycles:
        mask = df['half cycle'] == half_cycle
        x = df[mask]['Capacity']
        y = df[mask]['Voltage']
        xs.append(x)
        ys.append(y)

    source.data = dict(xs=xs, ys=ys)

for w in [cycle]:
    w.on_change('value', update_data)


# Set up layouts and add to document
inputs = column(text, cycle)

curdoc().add_root(row(inputs, plot, width=800))
curdoc().title = "Charge discharge plot"
