import pandas as pd
from markdown_pdf import MarkdownPdf, Section
from plot import bar_graph
from choropleth import choropleth_map

import os

def function(rows):
    df = pd.DataFrame(rows)   

    # create the .png files from the previous plot/choropleth examples
    bar_graph(df, model_output('building-damage-states.png'))
    choropleth_map(df, model_output('regional-collapsed-buildings.png'))
    
    # work out some total numbers to insert into the report
    states = ['None', 'Light', 'Minor', 'Moderate', 'Severe', 'Collapse']
    totals = {}
    total_damaged = 0
    # use 'table' to shuffle around the dataframe structure slightly
    table = df[["Region"] + states].copy()
    table["Region"] = table["Region"].map(lambda x: x["Region"])

    for state in states:
        table[state] = table[state].map(lambda x: x["count"])        
        totals[state] = table[state].sum()
        if state != 'None':
            total_damaged += totals[state]

    # replace the {placeholder} values in the template with the actual results
    with open(os.path.dirname(__file__) + "/template.md") as template:
        text = template.read().format(
            total_damaged=total_damaged,
            total_buildings=sum(totals.values()),
            total_collapsed=totals['Collapse']
        )

    # insert the simplified table of results
    text += "\n" + table.to_markdown(index=False)

    with open(os.path.dirname(__file__) + "/style.css") as file:
        style = file.read()
    pdf = MarkdownPdf()
    pdf.add_section(Section(text), user_css=style)
    pdf.save(model_output('Report-Summary.pdf'))
