import plotly as py
import plotly.graph_objs as graph

def choose_color(entropy):
    """ Calculates color for bare with given entropy """

    red = round(255 * entropy**5)
    green = round(255 * ((1 - (entropy - 0.5)**2 )/8)**0.6 )
    blue = round(255 * (1 - 0.8 * entropy**0.05))
    alpha = 0.6 + round(0.3 * entropy * 100)/100.0

    return (red, green, blue, alpha)

def create_annotations(entropy_data, block_descriptions, file_parts):
    """ Returns annotations - block labels - in plotly style """

    return [ dict (
        x=block_descriptions[i][0],
        y=entropy_data[i][0],
        xref='x',
        yref='y',
        text=str(file_parts[i]),
        showarrow=True,
        arrowhead=4,
        ax=0,
        ay=-40
    ) for i in range(len(entropy_data))]

def create_plot(entropy_data, block_descriptions):
    """ Returns colored plotly bar with entropy data """

    entropy_data = sum(entropy_data, [])

    return graph.Bar(
        y=entropy_data,
        x=sum(block_descriptions, []),
        marker=dict(
        color=['rgba' + str(choose_color(x)) for x in entropy_data]),
    )

def plot_page(bar, title, name, annotations = []):
    """ Converts plotly bar to .html page """

    layout = graph.Layout(title=title, annotations = annotations, )
    figure = graph.Figure(data=[bar], layout=layout)

    # Runs plot page
    py.offline.plot(figure, filename=(name + '.html'))

def save_to_file(bar, title, name, width=1024, height=640):
    """ Converts plotly bar to page downloading .png file """

    layout = graph.Layout(title=title, width=width, height=height)
    figure = graph.Figure(data=[bar], layout=layout)

    # Usability of this function is low as it runs plotly page
    # We should consider writing alternative solution...
    # in the distant future. (And in R.)
    py.offline.plot(figure, image='png')

if __name__ == "__main__":
    """ Part to check if plots creating works fine """

    example_data = [ [1 - float(i)/x for i in range(x)] for x in [30, 150, 40] ]
    example_desc = [ [i + (30 if x==150 else (180 if x==40 else 0)) for i in range(x)]
        for x in [30, 150, 40] ]
    example_parts= ['Start', 'Mid', 'End']
    annotations = create_annotations(example_data, example_desc, example_parts)
    bar = create_plot(example_data, example_desc)

    save_to_file(bar, 'Example file title', 'examplename')
    print("Page downloading .png file created!")
    plot_page(bar, 'Example title', 'examplename', annotations)
    print(".html file created - should open in browser autamaticly.")
