import pandas as pd
from pathlib import Path
from mail import mail
import config

cfg = config.config()
report_dir = cfg.portal_dir + '\\System\\Report'
publish_dir = cfg.portal_dir + '\\Publish\\daten'


def html_mail(content):
    html = """
        <!DOCTYPE html>
        <html><head>
            <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
            <style>
                .liste { border: 1px solid #888888; border-collapse: collapse; }
                .liste td, .liste th { padding: 3px 15px; border: 1px solid #888888; }
            </style>
        </head><body>
            <table class="liste"><tr><th>Datei</th><th>Bericht</th><th>Schicht</th><th>Stand</th><th>Empf&auml;nger</th></tr>
            {0}
            </table>
        </body></html> """
    return html.replace('{0}', content)


xml_filename = 'GAPS_Vers_taeglich_MO'
publish_subdir = publish_dir + '\\' + xml_filename
xml_filename = xml_filename.lower() + '.xml'

df = pd.read_csv(cfg.xml_dir + '\\info\\versand.csv', sep=';')
xml_filter = (df['Datei'].str.lower() == xml_filename) & (df['Versand'] == 'J')
df = df[xml_filter]
report_mails = df.groupby(['Report', 'PDF-Schicht']).agg(lambda x: ',<br/> '.join(x))['Empfaenger']
mail_batch = []

for group_name, df_group in df.groupby('Empfaenger'):
    group_table = []
    group_filenames = []
    for i, row in df_group.iterrows():
        filename = f"{publish_subdir}\\{row['Report']}_{row['PDF-Schicht']}"
        filename = filename + '.xls' if row['XLS'] == 'J' else filename + '.pdf'

        row['Empfaenger'] = report_mails.at[row['Report'], row['PDF-Schicht']]
        row['Dateiname'] = []
        row['Stand'] = 'nicht verf&uuml;gbar'
        if Path(filename).exists():
            row['Stand'] = Path(filename).stat().st_mtime
            row['Dateiname'].append((row['Name'], filename))
            group_filenames.append((row['Name'], filename))

        table_row = f"<tr><td>{row['Name']}</td><td>{row['Report']}</td><td>{row['PDF-Schicht']}</td><td>{row['Stand']}</td><td>{row['Empfaenger']}</td></tr>"
        group_table.append(table_row)

        if cfg.versand_separat:
            mail_batch.append((group_name, row['Name'], html_mail(table_row), row['Dateiname']))

    if not cfg.versand_separat:
        mail_batch.append((group_name, 'GAPS-Versand', html_mail(''.join(group_table)), group_filenames))


with mail() as m:
    for e in mail_batch:
        m.send(*e)