import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import dash_daq as daq
import dash_bootstrap_components as dbc
from datetime import datetime as dt
import plotly.graph_objects as go

#supress SettingWithCopyWarning 
pd.options.mode.chained_assignment = None

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
                   
def process_data():
    # important info! -> numbers 265 and 135 are for skipping first test measurements. In case of new database or own measurements 
    # it will be needed to be eaither removed or replaced with own number. It can be apssed as parameter or additional postprocessing is needed to exclude sleeceted data.
    df_signal = pd.read_csv('signal.csv',delimiter=',',usecols=[2,4,10,11],skiprows=[i for i in range(1,265)],nrows=21221) 
    df_data = pd.read_csv('data_latest.csv',delimiter=';',parse_dates=['time'],skiprows=[i for i in range(1,135)],nrows=1924) 
    
    #exclude false reading(might be depcrecated in newer version). It is because ofm ultiple values of qci and rssnr. Script only take first valid option -> for future work it is worth to rework
    df = df_signal[df_signal['time_ns'] > 0]

    #drop duplacate names of tests. Caution it takes only first valid numbers, but there are more valid numbers of qci and rssnr
    df = (df.drop_duplicates(['open_test_uuid']))
     
    # This will modify 'token' column in orginal dataframe. Because we want to merge files based on common value, only common value is first part of 'token' string in df_data and
    # 'open_test_uuid' in df_signal. Separator in token is '_' so anything after this separator is deleted and values are ready to merge
    f = lambda x: (x["token"].split("_")[0])
    df_data["token"] = df_data.apply(f, axis=1)

    
    df3 = pd.merge(df_data, df, how='left', left_on='token', right_on='open_test_uuid') 

    return df3

df_glob = process_data()

def handle_overhead(dropdown_val):
    if (dropdown_val == 'speed_upload' ):
       myStruct = {'yaxis': dropdown_val,
                   'line_shape': 'spline', # linear | spline | vhv | hvh | vh | hv
                   'main_title' : 'Rýchlosť nahrávania',
                   'yaxis_title' : 'Rýchlosť nahrávania [Mb/s]',
                   'divider' : 1000,
                   'yaxis_bot_val' : 0,
                   'yaxis_top_val' : 15}
    elif (dropdown_val == 'speed_download' ):
       myStruct = {'yaxis': dropdown_val,
                   'line_shape': 'spline', # linear | spline | vhv | hvh | vh | hv
                   'main_title' : 'Rýchlosť sťahovania',
                   'yaxis_title' : 'Rýchlosť sťahovania [Mb/s]',
                   'divider' : 1000,
                   'yaxis_bot_val' : 0,
                   'yaxis_top_val' : 21}
    elif (dropdown_val == 'ping_shortest' ):
       myStruct = {'yaxis': dropdown_val,
                   'line_shape': 'spline', # linear | spline | vhv | hvh | vh | hv
                   'main_title' : 'Rýchlosť odozvy',
                   'yaxis_title' : 'Odozva [ms]',
                   'divider' : 1000000,
                   'yaxis_bot_val' : 0,
                   'yaxis_top_val' : 40}
    elif (dropdown_val == 'ping_median' ):
       myStruct = {'yaxis': dropdown_val,
                   'line_shape': 'spline', # linear | spline | vhv | hvh | vh | hv
                   'main_title' : 'Medián odozvy',
                   'yaxis_title' : 'Odozva [ms]',
                   'divider' : 1000000,
                   'yaxis_bot_val' : 0,
                   'yaxis_top_val' : 40} 
    elif (dropdown_val == 'lte_rsrp' ):
       myStruct = {'yaxis': dropdown_val,
                   'line_shape': 'hvh', # linear | spline | vhv | hvh | vh | hv
                   'main_title' : 'Meranie intenzity signálu',
                   'yaxis_title' : 'RSRP [dBm]',
                   'divider' : 1,
                   'yaxis_bot_val' : -115,
                   'yaxis_top_val' : -90} 
    elif (dropdown_val == 'lte_rsrq' ):
       myStruct = {'yaxis': dropdown_val,
                   'line_shape': 'hvh', # linear | spline | vhv | hvh | vh | hv
                   'main_title' : 'Meranie referenčnej kvality signálu',
                   'yaxis_title' : 'RSRQ [dB]',
                   'divider' : 1,
                   'yaxis_bot_val' : -25,
                   'yaxis_top_val' : 0}    
    elif (dropdown_val == 'lte_rssnr' ):
       myStruct = {'yaxis': dropdown_val,
                   'line_shape': 'hvh', # linear | spline | vhv | hvh | vh | hv
                   'main_title' : 'Meranie referenčného pomeru signálu k šumu',
                   'yaxis_title' : 'RSSNR [dB]',
                   'divider' : 1,
                   'yaxis_bot_val' :-10,
                   'yaxis_top_val' : 10}     
    elif (dropdown_val == 'lte_cqi' ):
       myStruct = {'yaxis': dropdown_val,
                   'line_shape': 'hvh', # linear | spline | vhv | hvh | vh | hv
                   'main_title' : 'Indikátor kvality signálu',
                   'yaxis_title' : 'CQI [-]',
                   'divider' : 1,
                   'yaxis_bot_val' :0,
                   'yaxis_top_val' :16}      
       
    return myStruct

def day_in_week(day):
    if(day == 0):
        return ('Pondelok')
    elif (day == 1):
        return ('Utorok')
    elif (day == 2):
        return ('Streda')
    elif (day == 3):
        return ('Štvrtok')
    elif (day == 4):
        return ('Piatok')
    elif (day == 5):
        return ('Sobota')
    else:
        return ('Nedeľa')

def main_graph(dropdown_val):
    df_local = df_glob.copy(deep=True)
    attributes_loc = handle_overhead(dropdown_val)

    data = [go.Scatter(x=list(df_local['time']),
                    y=list(df_local[dropdown_val]/attributes_loc['divider']),
                    mode='lines',
                    line_shape=attributes_loc['line_shape'],
                    connectgaps=True,
                    line=dict(width=2))]


    layout1 = go.Layout(
        showlegend = False,
        xaxis = dict(title = dict(text = 'Čas',
                                  standoff = 40,
                                  font=dict(size=20)), 
                     tickangle = 45,
                     tickfont=dict(size=16),
                     rangeslider=dict(visible=True)
        ),
        yaxis = dict(title = dict(text = attributes_loc['yaxis_title'],
                                  font = dict(size=20)),
                    tickfont=dict(size=16)              
        ),

        title = dict(text = '<b>' + attributes_loc['main_title']+'</b>',
                     xanchor = 'center',
                     y =0.94,
                     x =0.5,
                     font=dict(size=20)),
        ) 

    fig1 = go.Figure(data=data, layout=layout1)
  
    return fig1

def range_of_dates(date_from,date_to,dropdown_val):
    #there is no need to load dataframe localy in this function because we dont need to recreate another dataframe, just read from glob
    attributes_loc = handle_overhead(dropdown_val)
    datum1 = pd.Timestamp(date_from).normalize().tz_localize(tz = 'CET') 
    datum2 = pd.Timestamp(date_to).normalize().tz_localize(tz = 'CET') #UTC
    mask = (df_glob['time'] > datum1)  & (df_glob['time'] <= datum2)
 
    data = [go.Scatter(x=list(df_glob.loc[mask]['time']),
                    y=list(df_glob.loc[mask][dropdown_val]/attributes_loc['divider']),
                    mode='lines',
                    line_shape=attributes_loc['line_shape'],
                    connectgaps=True,
                    line=dict(width=3))]

    layout1 = go.Layout(
        xaxis = dict(title = dict(text = 'Čas',
                                  standoff = 40,
                                  font=dict(size=20)), 
                     type='date',
                     tickangle = 45,
                     tickfont=dict(size=16)
        ),

        yaxis = dict(title = dict(text = attributes_loc['yaxis_title'],
                                  font = dict(size=20)),
                    range=[attributes_loc['yaxis_bot_val'], attributes_loc['yaxis_top_val']],
                    tickfont=dict(size=16)              
        ),

        title = dict(text = '<b>'+ attributes_loc['main_title'] + '</b>',
                     xanchor = 'center',
                     y =0.94,
                     x =0.5,
                     font=dict(size=20)),
        )              


    fig = go.Figure(data=data, layout=layout1)

    return fig

def graph_weekday(weekday,dropdown_val):
    df_loc = df_glob.copy(deep=True)
    attributes_loc = handle_overhead(dropdown_val)

    df_time = df_loc[df_loc['time'].dt.weekday == weekday]
    df_loc['date'] = pd.to_datetime(df_loc['time']).dt.date
    df_loc['time'] = pd.to_datetime(df_loc['time']).apply(lambda x: x.replace(year=1990, month=1, day=1))
    df_time['date'] = pd.to_datetime(df_time['time']).dt.date

    # extract the list of dates
    dates = list(df_time['date'].sort_values().unique())

    # generate the traces for the first date
    df_new = df_loc[df_loc['date'] == dates[0]]

    data = [go.Scatter(x=list(df_new['time']),
                    y=list(df_new[dropdown_val]/attributes_loc['divider']),
                    name=str(dates[0]),
                    mode='markers+lines',
                    connectgaps=True,
                    line_shape=attributes_loc['line_shape'],
                    legendgroup = 'Different',
                    line=dict(width=3))]

    # add the traces for the subsequent dates
    for date in dates[1:]:

        df_new = df_loc[df_loc['date'] == date]

        data.append(go.Scatter(x=list(df_new['time']),
                            y=list(df_new[dropdown_val]/attributes_loc['divider']),
                            name=str(date),
                            mode='markers+lines',
                            connectgaps=True,
                            line_shape=attributes_loc['line_shape'],
                            line=dict(width=3)))

    # define the figure layout
    layout = dict(xaxis=dict(title='Čas',range=[df_new['time'].min(), df_new['time'].max()],
                            tickformat='%H:%M',
                            type='date',
                            autorange=False),
                 title='Zmerane rýchlosti v určitom dni',
                 yaxis=dict(title='Rýchlosť sťahovania [Mb/s]'))

    layout1 = go.Layout(
        xaxis = dict(title = dict(text = 'Čas',
                                  standoff = 40,
                                  font=dict(size=20)), 
                     range=[df_new['time'].min(), df_new['time'].max()],
                     tickformat='%H:%M',
                     type='date',
                     tick0 = '00:00',
                     dtick = 60*60*1000,
                     tickangle = 45,
                     tickfont=dict(size=16)
        ),

        yaxis = dict(title = dict(text = attributes_loc['yaxis_title'],
                                  font = dict(size=20)),
                    range=[attributes_loc['yaxis_bot_val'], attributes_loc['yaxis_top_val']],
                    tickfont=dict(size=16)              
        ),

        title = dict(text = '<b>'+ attributes_loc['main_title'] + '</b>',
                     xanchor = 'center',
                     y =0.94,
                     x =0.5,
                     font=dict(size=20)),
        
        legend = dict(tracegroupgap = 10,
                      x=1,
                      y=1,
                      bordercolor="Black",
                      borderwidth=2,
                      font=dict(size=14))
        )


    fig3 = go.Figure(data=data, layout=layout1)

    return fig3

def two_dates_same_var(datum1,datum2,dropdown_val):
    df_loc = df_glob.copy(deep=True)
    attributes_loc = handle_overhead(dropdown_val)
    
    df_loc['date'] = pd.to_datetime(df_loc['time']).dt.date
    df_loc['time'] = pd.to_datetime(df_loc['time']).apply(lambda x: x.replace(year=1990, month=1, day=1))

    # extract the list of dates
    dates = list(df_loc['date'].sort_values().unique())

    # generate the traces for the first date
    df_new = df_loc[df_loc['date'] == pd.to_datetime(datum1).date()]

    data = [go.Scatter(x=list(df_new['time']),
                    y=list(df_new[dropdown_val]/attributes_loc['divider']),
                    name=str(datum1) + ' (' + str(day_in_week(pd.to_datetime(datum1).dayofweek)) + ')',
                    mode='markers+lines',
                    line_shape=attributes_loc['line_shape'],
                    connectgaps=True,
                    line=dict(width=3))]


    df_new = df_loc[df_loc['date'] == pd.to_datetime(datum2).date()]

    data.append(go.Scatter(x=list(df_new['time']),
                            y=list(df_new[dropdown_val]/attributes_loc['divider']),
                            name=str(datum2) + ' (' + str(day_in_week(pd.to_datetime(datum2).dayofweek)) + ')',
                            mode='markers+lines',
                            line_shape=attributes_loc['line_shape'],
                            connectgaps=True,
                            line=dict(width=3)))

    layout1 = go.Layout(
        xaxis = dict(title = dict(text = 'Čas',
                                  standoff = 40,
                                  font=dict(size=20)), 
                     type='date',
                     tick0 = '00:00',
                     dtick = 60*60*1000,
                     tickformat='%H:%M',
                     tickangle = 45,
                     tickfont=dict(size=16),
                     range = ["00:00","23:00"]
        ),
        #range = ["00:00",pd.to_datetime('2020-04-04 20:00').time()]
        yaxis = dict(title = dict(text = attributes_loc['yaxis_title'],
                                  font = dict(size=20)),
                    range=[attributes_loc['yaxis_bot_val'], attributes_loc['yaxis_top_val']],
                    tickfont=dict(size=16)              
        ),

        title = dict(text = '<b>'+ attributes_loc['main_title'] + '</b>',
                     xanchor = 'center',
                     y =0.94,
                     x =0.5,
                     font=dict(size=20)),

        legend = dict(tracegroupgap = 15,
                      x=0.8,
                      y=1,
                      bordercolor="Black",
                      borderwidth=2,
                      font=dict(size=16))
        )


    fig = go.Figure(data=data, layout=layout1)

    return fig

def mean_from_variable(df_glob,dropdown_val):
        df_loc = df_glob.copy(deep=True)
        df_loc['hour'] = pd.to_datetime(df_glob['time']).dt.hour
        attributes_loc = handle_overhead(dropdown_val)

        time_loc  = pd.date_range("00:00", "23:59", freq="60min").time

        std_loc = df_loc.groupby('hour').std()
        mean_loc  = df_loc.groupby(df_loc['hour']).mean()

        upper_bound = go.Scatter(
            name='Horné pásmo',
            x=time_loc,
            y=mean_loc[attributes_loc['yaxis']]/attributes_loc['divider']+std_loc[attributes_loc['yaxis']]/attributes_loc['divider'], 
            mode='lines',
            marker=dict(color="#444"),
            line=dict(width=0),
            fillcolor='rgba(68, 68, 68, 0.3)',
            fill='tonexty',
            line_shape='spline')

        trace = go.Scatter(
            name='Priemer',
            x=time_loc,
            y=mean_loc[attributes_loc['yaxis']]/attributes_loc['divider'], 
            mode='lines',
            line=dict(color='rgb(31, 119, 180)'),
            fillcolor='rgba(68, 68, 68, 0.3)',
            fill='tonexty',
            line_shape='spline')

        lower_bound = go.Scatter(
            name='Dolné pásmo',
            x=time_loc,
            y=mean_loc[attributes_loc['yaxis']]/attributes_loc['divider']-std_loc[attributes_loc['yaxis']]/attributes_loc['divider'], 
            marker=dict(color="#444"),
            line=dict(width=0),
            mode='lines',
            line_shape='spline')

        # Trace order is important
        data = [lower_bound, trace, upper_bound]

        layout1 = go.Layout(
        showlegend = False,
        xaxis = dict(title = dict(text = 'Čas',
                                  standoff = 40,
                                  font=dict(size=20)), 
                     tickangle = 45,
                     tickfont=dict(size=16),
        ),
        yaxis = dict(title = dict(text = attributes_loc['yaxis_title'],
                                  font = dict(size=20)),
                    tickfont=dict(size=16)              
        ),

        title = dict(text = '<b>Priemer a smerodajná odchýlka - </b>'+'<b>'+attributes_loc['main_title']+'</b>',
                     xanchor = 'center',
                     y =0.94,
                     x =0.5,
                     font=dict(size=20)),
        )

        fig = go.Figure(data=data, layout=layout1)
        return fig

def average_all_days(df_glob,dropdown_val):
    df_local = df_glob.copy(deep=True)
    df_time = df_local[df_local['time'].dt.weekday == 0]
    attributes_loc = handle_overhead(dropdown_val)
  
    df_local['date'] = pd.to_datetime(df_local['time']).dt.date
    df_local['time'] = pd.to_datetime(df_local['time']).apply(lambda x: x.replace(year=1990, month=1, day=1))
    df_time['date'] = pd.to_datetime(df_time['time']).dt.date

    # extract the list of dates
    dates = list(df_time['date'].sort_values().unique())

    df_new = df_local[df_local['date'] == dates[0]]
    
    for date in dates[1:]:
        df_temp = df_local[df_local['date'] == date]
        df_new = df_new.append(df_temp)
           
    df_new['hour'] = pd.to_datetime(df_new['time']).dt.hour

    xaxis_time  = pd.date_range("00:00", "23:59", freq="60min").time
    time_loc1  = pd.date_range("00:00", "23:59", freq="H")
    mean_loc  = df_new.groupby(df_new['hour']).mean()

    trace = [go.Scatter(
        name=day_in_week(0),
        x=time_loc1,
        y=mean_loc[attributes_loc['yaxis']]/attributes_loc['divider'],
        mode='markers+lines',
        line_shape='spline',
        legendgroup = 'Different',
        line=dict(width=4))]

    
    for den in range(1,7):
        df_local = df_glob.copy(deep=True)
        df_time = df_local[df_local['time'].dt.weekday == den]

        df_local['date'] = pd.to_datetime(df_local['time']).dt.date
        df_local['time'] = pd.to_datetime(df_local['time']).apply(lambda x: x.replace(year=1990, month=1, day=1))
        df_time['date'] = pd.to_datetime(df_time['time']).dt.date

        # extract the list of dates
        dates = list(df_time['date'].sort_values().unique())

        df_new = df_local[df_local['date'] == dates[0]]
        
        # for date in dates[1:]:
        for date in dates[1:]:
            df_temp = df_local[df_local['date'] == date]
            df_new = df_new.append(df_temp)
            
        df_new['hour'] = pd.to_datetime(df_new['time']).dt.hour

        time_loc1  = pd.date_range("00:00", "23:59", freq="H")
        std_loc = df_new.groupby('hour').std()
        mean_loc  = df_new.groupby(df_new['hour']).mean()


        trace.append(go.Scatter(
            name=day_in_week(den),
            x=time_loc1,
            y=mean_loc[attributes_loc['yaxis']]/attributes_loc['divider'],
            mode='markers+lines',
            line_shape='spline',
            line=dict(width=3)))  

        
    layout1 = go.Layout(
        xaxis = dict(title = dict(text = 'Čas',
                                  standoff = 40,
                                  font=dict(size=20)), 
                     type='date',
                     tick0 = '00:00',
                     dtick = 60*60*1000,
                     tickformat='%H:%M',
                     tickangle = 45,
                     tickfont=dict(size=16)
        ),

        yaxis = dict(title = dict(text =attributes_loc['yaxis_title'],
                                  font = dict(size=20)),
                    tickfont=dict(size=16)              
        ),

        title = dict(text = '<b>Priemer za jednotlivé dni</b>',
                     xanchor = 'center',
                     y =0.94,
                     x =0.5,
                     font=dict(size=20)),

        legend = dict(tracegroupgap = 15,
                      x=1,
                      y=1,
                      bordercolor="Black",
                      borderwidth=2,
                      font=dict(size=16))
        )

    fig = go.Figure(data=trace, layout=layout1)
    return fig

##------------------Global variables-----------------------------------------------------
column_names = list(df_glob.columns)

bottom = df_glob['time'].tail(1)     # first accesible value of calendar     
top = df_glob['time'].head(1)        # last accesible value of calendar
##------------------Global initializtion of figures--------------------------------------
fig1 = main_graph(column_names[11])
fig2 = range_of_dates(dt(2020, 4, 17),dt(2020, 4, 21),column_names[11])
fig3 = graph_weekday(0,column_names[11])
fig4 = mean_from_variable(df_glob,column_names[11])
fig5 = average_all_days(df_glob,column_names[12])
fig6 = two_dates_same_var(dt(2020,5,9).date(),dt(2020,4,4).date(),column_names[11])
##------------------Global initializtion of figures--------------------------------------



app = dash.Dash(__name__,external_stylesheets=external_stylesheets)
  
app.layout = html.Div([
    dcc.Tabs(
        id="tabs-with-classes",
        value='tab-4',
        parent_className='custom-tabs',
        className='custom-tabs-container', 
        children=[
         dcc.Tab(
            html.Div([
                html.Div([
                dcc.Dropdown(
                id='demo-dropdown',
                options=[
                    {'label': 'Upload', 'value': column_names[11]},
                    {'label': 'Download', 'value': column_names[12]},
                    {'label': 'Ping', 'value': column_names[13]},
                    {'label': 'Ping medián', 'value': column_names[104]},
                    {'label': 'RSRP', 'value': column_names[97]},
                    {'label': 'RSRQ', 'value': column_names[98]},
                    {'label': 'RSSNR', 'value': column_names[140]},
                    {'label': 'CQI', 'value': column_names[141]}
                ],
                value = column_names[11],
                style=dict(
                            width='100%',
                        ) 
                ),
                ]),

                html.Div([
                    dcc.Graph(id = 'graf1', 
                            figure = fig1,
                            style={'height': 800},
                            config = {"toImageButtonOptions": dict(width=1920,height=1080,format='svg')}),
                            
                ])
            
            ]),
            label='Kompletné meranie',
            value='tab-1',
            className='custom-tab',
            selected_className='custom-tab--selected'
         ),

         dcc.Tab(
            html.Div([
                html.Div([
                    dcc.DatePickerRange(
                        id='my-date-picker-range',
                        start_date=dt(2020, 5, 6),
                        min_date_allowed= df_glob.time[top.index.min()].date(),
                        max_date_allowed= df_glob.time[bottom.index.min()].date(),
                        initial_visible_month=dt(2020, 5, 9),
                        end_date=dt(2020, 5, 9)
                    )
                    ]),
                    html.Div([
                    dcc.Dropdown(
                        id='dropdown_tab2',
                        options=[
                            {'label': 'Upload',       'value': column_names[11]},
                            {'label': 'Download',     'value': column_names[12]},
                            {'label': 'Ping',         'value': column_names[13]},
                            {'label': 'Ping medián',  'value': column_names[104]},
                            {'label': 'RSRP',         'value': column_names[97]},
                            {'label': 'RSRQ',         'value': column_names[98]},
                            {'label': 'RSSNR',        'value': column_names[140]},
                            {'label': 'CQI',          'value': column_names[141]}
                        ],
                        value = column_names[12],
                        clearable=False,
                        style=dict(
                                    width='33%',
                                ) 
                        )
                    ]),
        
                html.Div([
                    dcc.Graph(id = 'graf2', 
                            figure=fig2,
                            style={'height': 800},
                            config={"toImageButtonOptions": dict(width=1920,height=1080,format='svg')}),
                ]),
            ]),

            label='Merania v rozsahu dní',
            value='tab-2',
            className='custom-tab',
            selected_className='custom-tab--selected'
         ),

          dcc.Tab(
              html.Div([
                html.Div([
                    dcc.Dropdown(
                        id='dropdown_graf3',
                        options=[
                            {'label': 'Pondelok', 'value': 0},
                            {'label': 'Utorok',   'value': 1},
                            {'label': 'Streda',   'value': 2},
                            {'label': 'Štvrtok',  'value': 3},
                            {'label': 'Piatok',   'value': 4},
                            {'label': 'Sobota',   'value': 5},
                            {'label': 'Nedeľa',   'value': 6}
                        ],
                    value = 5,
                    style=dict(width='33%') 
                    ),
                ]),
                html.Div([
                dcc.Dropdown(
                        id='dropdown_tab3',
                        options=[
                            {'label': 'Upload',       'value': column_names[11]},
                            {'label': 'Download',     'value': column_names[12]},
                            {'label': 'Ping',         'value': column_names[13]},
                            {'label': 'Ping medián',  'value': column_names[104]},
                            {'label': 'RSRP',         'value': column_names[97]},
                            {'label': 'RSRQ',         'value': column_names[98]},
                            {'label': 'RSSNR',        'value': column_names[140]},
                            {'label': 'CQI',          'value': column_names[141]}
                        ],
                        value = column_names[11],
                        clearable=False,
                        style=dict(
                                    width='33%',
                                ) 
                        )
                ]),

                html.Div([
                dcc.Graph(id = 'graf3', 
                        figure=fig3,
                        style={'height': 800},
                        config={"toImageButtonOptions": dict(width=1920,height=1080,format='svg')}),
               ]),
            ]),
            label='Všetky merania v určený deň',
            value='tab-3',
            className='custom-tab',
            selected_className='custom-tab--selected'
            ),


         dcc.Tab(
             html.Div([
                 html.Div([
                    dcc.Dropdown(
                        id='dropdown_tab4',
                        options=[
                            {'label': 'Upload',       'value': column_names[11]},
                            {'label': 'Download',     'value': column_names[12]},
                            {'label': 'Ping',         'value': column_names[13]},
                            {'label': 'Ping medián',  'value': column_names[104]},
                            {'label': 'RSRP',         'value': column_names[97]},
                            {'label': 'RSRQ',         'value': column_names[98]},
                            {'label': 'RSSNR',        'value': column_names[140]},
                            {'label': 'CQI',          'value': column_names[141]}
                        ],
                        value = column_names[12],
                        clearable=False,
                        style=dict(
                                    width='33%',
                                ) 
                        )
                ]),  

            html.Div([
                    dcc.Graph(id = 'graf4', 
                            figure=fig4,
                            style={'height': 800},
                            config={"toImageButtonOptions": dict(width=1920,height=1080,format='svg')}),
            ]),

             ]),
            label='Celkový priemer a smerodajná odchýlka',
            value='tab-4',
            className='custom-tab',
            selected_className='custom-tab--selected'
            ),

            dcc.Tab(
               html.Div([
                 html.Div([
                    dcc.Dropdown(
                        id='dropdown_tab5',
                        options=[
                            {'label': 'Upload',       'value': column_names[11]},
                            {'label': 'Download',     'value': column_names[12]},
                            {'label': 'Ping',         'value': column_names[13]},
                            {'label': 'Ping medián',  'value': column_names[104]},
                            {'label': 'RSRP',         'value': column_names[97]},
                            {'label': 'RSRQ',         'value': column_names[98]},
                            {'label': 'RSSNR',        'value': column_names[140]},
                            {'label': 'CQI',          'value': column_names[141]}
                        ],
                        value = column_names[12],
                        clearable=False,
                        style=dict(
                                    width='33%',
                                ) 
                        )
                ]),

               html.Div([
                    dcc.Graph(id = 'graf5', 
                            figure=fig5,
                            style={'height': 800},
                            config={"toImageButtonOptions": dict(width=1920,height=1080,format='svg')}),
               ]),
            ]),
            label='Priemer za jednotlivé dni',
            value='tab-5',
            className='custom-tab',
            selected_className='custom-tab--selected'
            ),


            dcc.Tab(
            html.Div([
                html.Div([
                    dcc.DatePickerSingle(
                        id = 'first_date',
                        min_date_allowed= df_glob.time[top.index.min()].date(),
                        max_date_allowed= df_glob.time[bottom.index.min()].date(),
                        
                        with_portal=True,
                        date=dt(2020,5,9).date()
                    ),
                    dcc.DatePickerSingle(
                        id = 'second_date',
                        min_date_allowed= df_glob.time[top.index.min()].date(),
                        max_date_allowed= df_glob.time[bottom.index.min()].date(),
                        
                        with_portal=True,
                        date=dt(2020,4,4).date()
                    )
                    ]),

                    html.Div([
                    dcc.Dropdown(
                        id='dropdown',
                        options=[
                            {'label': 'Upload',       'value': column_names[11]},
                            {'label': 'Download',     'value': column_names[12]},
                            {'label': 'Ping',         'value': column_names[13]},
                            {'label': 'Ping medián',  'value': column_names[104]},
                            {'label': 'RSRP',         'value': column_names[97]},
                            {'label': 'RSRQ',         'value': column_names[98]},
                            {'label': 'RSSNR',        'value': column_names[140]},
                            {'label': 'CQI',          'value': column_names[141]}
                        ],
                        value = column_names[11],
                        clearable=False,
                        style=dict(
                                    width='33%',
                                ) 
                        )
                    ]),


                html.Div([
                    dcc.Graph(id = 'graf6', 
                            figure=fig6,
                            style={'height': 800},
                            config={"toImageButtonOptions": dict(width=1920,height=1080,format='svg')}),
                ]),
            ]),

            label='Porovnanie dvoch dní',
            value='tab-6',
            className='custom-tab',
            selected_className='custom-tab--selected'
         )
    
        ]),
    html.Div(id='tabs-content-classes')
])



@app.callback(
    [dash.dependencies.Output('graf1', 'figure'),
    dash.dependencies.Output('graf2', 'figure'),
    dash.dependencies.Output('graf3', 'figure'),
    dash.dependencies.Output('graf4', 'figure'),
    dash.dependencies.Output('graf5', 'figure'),
    dash.dependencies.Output('graf6', 'figure')],
    [dash.dependencies.Input('demo-dropdown', 'value'),
    dash.dependencies.Input('my-date-picker-range', 'start_date'),
    dash.dependencies.Input('my-date-picker-range', 'end_date'),
    dash.dependencies.Input('dropdown_graf3', 'value'),
    dash.dependencies.Input('first_date', 'date'),
    dash.dependencies.Input('second_date', 'date'),
    dash.dependencies.Input('dropdown', 'value'),
    dash.dependencies.Input('dropdown_tab2', 'value'),
    dash.dependencies.Input('dropdown_tab3', 'value'),
    dash.dependencies.Input('dropdown_tab4', 'value'),
    dash.dependencies.Input('dropdown_tab5', 'value'),
    dash.dependencies.Input('tabs-with-classes', 'value')])
def update_output(dropdown_tab1,start_date,end_date,day_in_weekday,start_date1,end_date1,dropdown_tab6,dropdown_tab2,dropdown_tab3,dropdown_tab4,dropdown_tab5,tab):
    #global variables for return function. Return function calls all 6 figures at the same time but only one tab is updated. It returns nonupdated graphs therefore it save computing time
    #Consider if it will be more optimized with multiple callbacks (if there would be request for adding more outputs)
    global fig1,fig2,fig3,fig4,fig5,fig6
            
    if tab == 'tab-1':
         fig1 = main_graph(dropdown_tab1) 
    elif tab == 'tab-2':
        fig2 = range_of_dates(start_date,end_date,dropdown_tab2)
    elif tab == 'tab-3':
        fig3 = graph_weekday(day_in_weekday,dropdown_tab3) 
    elif tab == 'tab-4':
        fig4 = mean_from_variable(df_glob,dropdown_tab4)
    elif tab == 'tab-5':
        fig5 = average_all_days(df_glob,dropdown_tab5)
    elif tab == 'tab-6':
        fig6 = two_dates_same_var(start_date1,end_date1,dropdown_tab6)

    return (fig1,fig2,fig3,fig4,fig5,fig6)  



app.run_server(debug=True)














