from oilanalytics.iea import omr
from oilanalytics.opec import momr
from oilanalytics.eia import steo
from commodplot import commodplotutil as cpu
from commodplot import commodplot as cpl


colorder = [
    'Demand',
    'OECD',
    'Non-OECD',
    'Non-OPEC supply',
    'North America',
    'FSU',
    'OPEC NGLs/Condensates',
    'OPEC crude',
    'Stock change'
]


def balance_comparisons(additional_sources:dict=None):
    iea = omr.comparable_snd_table()
    iea = iea[iea.columns.intersection(colorder)]
    opec = momr.comparable_snd_table()
    opec = opec[opec.columns.intersection(colorder)]
    eia = steo.comparable_snd_table()
    eia = eia[eia.columns.intersection(colorder)]

    res = {
        'iea' : iea,
        'opec' : opec,
        'eia' : eia,
    }

    if additional_sources:
        for additional_source in additional_sources:
            res[additional_source] = additional_sources[additional_source]

    return res


def format_table(df):
    summary_table = cpl.table_plot(df, chtype='table', formatted_cols=['Change', '%'])
    format_dict = {'height': 30, 'font': {'size': 10}}
    summary_table.update_traces({'cells': format_dict, 'header': format_dict})
    return summary_table


def generate_comparisons_page(out_loc=None):
    if not out_loc:
        out_loc = 'BalanceComparison.html'
    d = balance_comparisons()
    data = {'name': 'Balance Comparisons', 'title': 'Balance Comparisons'}
    data['iea_table'] = format_table(d['iea'])
    data['eia_table'] = format_table(d['eia'])
    data['opec_table'] = format_table(d['opec'])
    cpu.render_html(data, 'balance_comparisons.html', out_loc, package_loader_name='balances')


if __name__ == '__main__':
    # balance_comparisons()
    generate_comparisons_page()