from webapp.selectors import filter_element, filter_element_range
from webapp.formatting import human_format
from dash import dcc, html
import dash_bootstrap_components as dbc

def categorical_attribute_filter(name, workflow, value):
    possible_values = workflow[workflow['attribute']==(name + '_attribute')]['values']
    dropdown = dcc.Dropdown(id='attribute-filter-' + name,
                 options=[{'label': value, 'value': value}
                         for value in possible_values],
                           multi=True,
                           value=value,
                           persistence=False,
                       style={'font-size': '12px',
                            'border-radius': 0})
    return dropdown

def numeric_attribute_filter(name, value=None):
    if value is None:
        value = [0, 100]
    return dbc.Col([dbc.Row(dcc.RangeSlider(min=0, 
                        max=100, 
                        step=1,
                        value=value,
                        marks=None,
                        allowCross=False,
                        id='attribute-filter-' + name,
                        persistence=False),
                    style={'margin': 0, 'padding-top': '5px', 
                               'z-index': '-1'}),
                     dbc.Row([dbc.Col(html.Div(id='min-attribute-filter-' + name), style={'margin': 0, 'padding': 0}, md=2),
                     dbc.Col(html.Div(), md=8), dbc.Col(html.Div(id='max-attribute-filter-' + name), style={'margin': 0, 'padding': 0, 'float': 'right'}, md=2)],
                            style={'margin-top': 0, 'margin-left': '20px', 'padding-right': '40px', 'position': 'absolute', 'top': '18px', 'width': '100%'})],
                  style={'position': 'relative'})
    return slider

def attribute_filter(name, workflow, is_numeric, value=None, min_value='Lowest', max_value='Highest'):
    if is_numeric:
        return filter_element_range(name, numeric_attribute_filter(name, value))
    else:
        return filter_element(name, categorical_attribute_filter(name, workflow, value))

def attribute_filters(attributes_values_df, attributes_columns, attributes_numeric, attribute_scales, filters=None):
    if filters is None:
        return [attribute_filter(col, attributes_values_df, True, min_value=human_format(attribute_scales[col][0]), max_value=human_format(attribute_scales[col][-1])) if attributes_numeric[i] == 1 else attribute_filter(col, attributes_values_df, False) for i, col in enumerate(attributes_columns)]
    else:
        return [attribute_filter(col, attributes_values_df, True, value=filters[col], min_value=human_format(attribute_scales[col][0]), max_value=human_format(attribute_scales[col][-1])) if attributes_numeric[i] == 1 else attribute_filter(col, attributes_values_df, False, value=filters[col]) for i, col in enumerate(attributes_columns)]
