from base64 import b64encode
from io import BytesIO

from folium import Map

from app.preprocessing import create_dataframe
from constants import COORDINATES


def get_figure(plot):
    plot_figure = plot.get_figure()
    figure = BytesIO()
    plot_figure.savefig(figure)
    figure.seek(0)
    return figure


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


def encode_plot(figure):
    plot = b64encode(figure.getvalue().decode())
    return plot


def create_plot(df):
    figure = render_plot(df)
    plot = encode_plot(figure)
    return plot


def create_map(df):
    map = Map(location=COORDINATES)
    for row in df.iterrows():
        map.simple_marker(
            location=[row["fields.geo_shape.coordinates"]], clustered_marker=True
        )
    return map


def process_data(dataset):
    df = create_dataframe(dataset)
    plot = create_plot(df)
    map = create_map(df)
    return plot, map
