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 = """
        
        
            
            
        
            | Datei | Bericht | Schicht | Stand | Empfänger | 
|---|
            {0}
            
         """
    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: ',
 '.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ü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"| {row['Name']} | {row['Report']} | {row['PDF-Schicht']} | {row['Stand']} | {row['Empfaenger']} | 
"
        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)