from app import db
from io import BytesIO
from pandas import DataFrame, read_sql
from base64 import b64encode


def create_dataframe(query) -> DataFrame:
    df = read_sql(sql=query, con=db.engine)
    return df


def render_table(df) -> str:
    df.fillna(value=0, inplace=True)
    table = df.to_html(classes=["table-striped", "table-hover"])
    return table


def render_plot(df):
    df.fillna(value=0, inplace=True)
    plot = df.plot("year", ["surface", "length", "elevation"], kind="bar")
    plot_figure = plot.get_figure()
    figure = BytesIO()
    plot_figure.savefig(figure)
    figure.seek(0)
    return figure


def encode_plot(plot):
    buffer = b"".join(plot)
    buf = b64encode(buffer)
    encoded_plot = buf.decode("utf-8")
    return encoded_plot


def create_table(query) -> str:
    df = create_dataframe(query)
    html_table = render_table(df)
    return html_table


def create_plot(query):
    df = create_dataframe(query)
    plot = render_plot(df)
    encoded_plot = encode_plot(plot)
    return encoded_plot
