import pkgutil


def apply_holoviews_theme(parsed_css):
    """
    A code generator used to set the holoviews theme from the parsed CSS.
    """
    hvavailable = pkgutil.find_loader('holoviews')
    if hvavailable is None: return
    if parsed_css == {}:
        return ''

    lines = ["import holoviews as hv",
             "from holoviews.plotting import bokeh",
             "from bokeh.themes.theme import Theme",
             "hv.renderer('bokeh').theme = Theme(json={json})"]

    bgcolor = parsed_css['body']['background-color']
    bgcolor = bgcolor if bgcolor != '#fff' else  '#ffffff'
    opposed = 'white' if bgcolor != '#ffffff' else 'black'
    theme = {
            'attrs' : {
                'Figure' : {
                    'background_fill_color': bgcolor,
                    'border_fill_color':     bgcolor,
                    'outline_line_color': '#444444',
                },
                'Grid': {
                    'grid_line_dash': [6, 4],
                    'grid_line_alpha': .3,
                },
                'Title': {
                    'text_color': opposed
                },
                'Axis': {
                    'axis_label_text_color': opposed,
                    'axis_line_color' : opposed,
                    'minor_tick_line_color' : opposed,
                    'major_label_text_color' : opposed,
                    'major_tick_line_color': opposed
                },
                'ColorBar': {
                    'background_fill_color' : bgcolor,
                    'title_text_color': opposed,
                    'major_label_text_color': opposed
                    }
            }
        }

    template = "\n".join(lines)
    return template.format(json=repr(theme))