from parameters import * #parameters read from other .py file
from pandasdmx import Request
from collections import OrderedDict
import pandas as pd
import math
from subprocess import call



from bokeh.io import curdoc, show
from bokeh.layouts import row, column, layout, widgetbox, Spacer
from bokeh.models import ColumnDataSource, DataRange1d, Select, DatetimeTickFormatter, NumeralTickFormatter, Plot, LinearAxis, Grid, LabelSet, Label, HoverTool, Div, CDSView, GroupFilter, Line, Legend, Title, FactorRange
from bokeh.palettes import Blues4, Spectral6, Category10, Spectral10
from bokeh.plotting import figure
from bokeh.models.glyphs import HBar, VBar
from bokeh.models.widgets import RadioButtonGroup, PreText,DataTable, DateFormatter, TableColumn, RadioGroup, Panel, Tabs, Toggle, Button

from pyjstat import pyjstat
import requests
from collections import OrderedDict
from sortedcontainers import SortedDict
import pickle

lokdisk = 1 #dali se rabotai za doma (1) ili na rabota (2)

def ReadM(estattable):
    if lokdisk == 1:
        pickle_out = "H:\\SDG\\pickle\\mk_" + estattable + ".pickle" #za doma
    else:
        pickle_out = "E:\\Goran\\bokeh\\pickle\mk\\" + estattable + ".pickle"  #za rabota
    pickle_off = open(pickle_out,"rb")
    dfmk = pickle.load(pickle_off)
    return dfmk
    


def ReadE(estattable, titles, sourcem, estatparam, dfmk):
    if lokdisk == 1:
        pickle_out = "H:\\SDG\\pickle\\" + estattable + ".pickle" #za doma
    else:
        pickle_out = "E:\\Goran\\bokeh\\pickle\eu\\" + estattable + ".pickle" #za rabota
    pickle_off = open(pickle_out,"rb")
    data = pickle.load(pickle_off)
	s2 = data.loc[:, estatparam.get(estattable)]
	
	df = s2.set_index(s2.index.get_level_values(0))
    s2.columns = s2.columns.droplevel()
    s2.columns = list(df.columns.levels[0])
    s3 = s2.to_timestamp(freq='D', how='s', copy=True)
    if sourcem.get(estattable) == '1':
        s3.drop(columns=['MK'], inplace=True)
        s3 = pd.merge(left=s3, right=dfmk, how='left', left_on=s3.index, right_on=dfmk.index)
        s3.rename(columns={'value': 'MK', 'key_0': 'TIME_PERIOD'}, inplace=True)
        s3.set_index(['TIME_PERIOD'], inplace=True)
    s4 = s3.loc[:, ('MK', 'EU28')]
    
    for q in range(1, 10):
        q1 = q*(-1)
        q2 = s3['MK'][q1]
        if math.isnan(q2):
            pass
        else:
            break
    

    s5 = s3.loc[(s3.index[q1]), :]
    s5.sort_values(axis=0, ascending=False, inplace=True)
    s5 = s5.to_frame()
    s5['new'] = s5.iloc[:,0]
    s5.drop(s5.columns[0], axis=1, inplace=True)
    s5['color'] = '#3288bd'
    s5.loc['MK','color'] = '#d53e4f'
    s5.drop('EU', inplace=True)
    s5.drop('EU27', inplace=True)
    s5.drop('EA19', inplace=True)
    s5.drop('EA18', inplace=True)
    year = s3.loc[(s3.index[q1]), :].name.year
    xx=s5.index.tolist()
    yy=s5['new'].tolist()
    colour = s5['color'].tolist()
    source = ColumnDataSource(data=s4)
    sourcebar = ColumnDataSource(dict(x=xx,top=yy, color=colour))
	
	return s3, s4, s5, source, sourcebar, year

def make_plotLine(source, title, subtitle, yunits):
    p2 = figure(x_axis_type="datetime", plot_width=800, plot_height=500)
    p21 = p2.line(x='TIME_PERIOD', y='EU28', source=source, line_width=4, color="blue", alpha=0.5)
    p22 = p2.line(x='TIME_PERIOD', y='MK', source=source, line_width=4, color="red", alpha=0.5)

    p2.title.align = 'center'
    p2.xaxis.axis_label = None
    p2.yaxis.axis_label = yunits
    p2.x_range = DataRange1d(range_padding=0.1)
    p2.grid.grid_line_alpha = 0.3
    p2.xaxis.formatter=DatetimeTickFormatter(
        years=["%Y"]
        )
    p2.min_border_bottom = 0
    p2.yaxis.minor_tick_line_color = None
    #p2.add_layout(Title(text=subtitle, text_font_style="italic"), 'above')
    #p2.add_layout(Title(text=title, text_font_size="16pt"), 'above')

    legend = Legend(items=[
        (s4.columns[0] , [p22]),
        (s4.columns[1] , [p21])
        ], location=(200, -10))

    p2.add_layout(legend, 'below')
    p2.lod_timeout
    p2.legend.click_policy="hide"
    p2.legend.orientation = "horizontal"
    return p2

    

def make_plotBar(sourcebar, title, subtitle, yunits):
    sortedc = sorted(list(sourcebar.data['x']), key=lambda x: list(sourcebar.data['top'])[list(sourcebar.data['x']).index(x)], reverse=True)
    print('Od makePlot   ', sortedc)
    p = figure(x_range=sortedc, plot_width=800, plot_height=500, toolbar_location=None)
    p.vbar(x='x', top='top', width=0.8, source=sourcebar, line_color='white', fill_color='color')
    p.xgrid.grid_line_color = None
    p.y_range.start = 0
    p.xaxis.major_label_text_font_size = "7pt"
    
    p.yaxis.axis_label = yunits

    #p.add_layout(Title(text=subtitle, text_font_style="italic"), 'above')
    #p.add_layout(Title(text=str(title + ', ' + str(year)), text_font_size="16pt"), 'above')
    return p

def update_plot(attrname, old, new):
    print("TUKA SUM VO UPDATE PLOT")
    estattable = list(radioButton.labels)[radioButton.active]
    
    if sourcem.get(estattable) == '1':
        dfmk = ReadM(estattable)
    else:
        dfmk = pd.DataFrame({'A' : []}) #empty dataframe
    s3, s4, s5, source1, sourcebar1, year = ReadE(estattable, titles, sourcem, estatparam, dfmk)
	
	title = titles.get(estattable)[0][0]
    subtitle = titles.get(estattable)[0][1]
    yunits = titles.get(estattable)[0][2]
        
    source.data.update(source1.data)
    sourcebar.data.update(sourcebar1.data)

    sortedc = sorted(list(sourcebar.data['x']), key=lambda x: list(sourcebar.data['top'])[list(sourcebar.data['x']).index(x)], reverse=True)
    

    #plot_line = make_plotLine(source, title, subtitle, yunits)
    #plot_bar = make_plotBar(sourcebar, title, subtitle, yunits)
    
    

    
    plot_bar.x_range.factors = sortedc
    #plot_bar.title.update(title, subtitle)
    plot_line.update
    plot_bar.update
    
    # ???????                      
    #plot_bar.add_layout(Title(text=subtitle, text_font_style="italic"), 'above')
    #plot_bar.add_layout(Title(text=str(title + ', ' + str(year)), text_font_size="16pt"), 'above')

   
    

estattable = list(SortedDict(indicators.get('1')).keys())[0]
title = titles.get(estattable)[0][0]
subtitle = titles.get(estattable)[0][1]
yunits = titles.get(estattable)[0][2]

if sourcem.get(estattable) == '1':
    dfmk = ReadM(estattable)
else:
    dfmk = pd.DataFrame({'A' : []}) #empty dataframe


s3, s4, s5, source, sourcebar, year = ReadE(estattable, titles, sourcem, estatparam, dfmk)

# Create Input controls
#How to set button with image as background and when click on the button to change plots with other data???
button1 = Button(label="", button_type="link", css_classes=['button_G1'])


sel = Select(title="Goals:", value="foo", options = list(map(str, goals.keys())))
radioButton = RadioButtonGroup(
    labels=list(SortedDict(indicators.get('1')).keys()),
    active=0, width=700,css_classes=['custom_button_1'])
radioButton.on_change('active', update_plot)

plot_line = make_plotLine(source, title, subtitle, yunits)
plot_bar = make_plotBar(sourcebar, title, subtitle, yunits)

plot_line.add_layout(Title(text=subtitle, text_font_style="italic"), 'above')
plot_line.add_layout(Title(text=title, text_font_size="16pt"), 'above')
    
plot_bar.add_layout(Title(text=subtitle, text_font_style="italic"), 'above')
plot_bar.add_layout(Title(text=str(title + ', ' + str(year)), text_font_size="16pt"), 'above')


tab2 = Panel(child=plot_line, title="Time serie")
tab1 = Panel(child=plot_bar, title="Comparison")

tabs = Tabs(tabs=[tab2, tab1 ])

rb1 = row(button1)

r = column(sel, rb1, tabs, radioButton)

curdoc().add_root(r)
curdoc().title = "Bokeh server app"
