import csv
from pathlib import Path
from mail import mail
from itertools import groupby
import config
import jinja2
from datetime import datetime


cfg = config.Config('GAPS3.ini')

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>
        {% for row in reports %}
            <tr>
                <td>{{row.Name}}</td><td>{{row.Report}}</td><td>{{row.Schicht}}</td>
                <td>{{row.Stand}}</td><td>{{row.Empfaenger}}</td>
            </tr>
        {% endfor %}
        </table>
    </body></html> """


def dispatch(xml_filename, recipient=None, report=None, cube=None):
    publish_subdir = config.joinpath(cfg.cognos7.publish_dir, xml_filename[:-4])

    with open(cfg.xml_dir + '/info/versand.csv', 'r') as frh:
        csv_reader = csv.DictReader(frh, delimiter=';')
        dispatch_list = [x for x in csv_reader]

    def dispatch_filter(x):
        return all([
            x['Datei'].lower() == xml_filename,
            x['Versand'] == 'J',
            (recipient is None or x['Empfaenger'] == recipient),
            (report is None or x['Report'].lower() == report.lower()),
            (cube is None or x['Cube'].lower() == cube.lower())
        ])

    dispatch_list = list(filter(dispatch_filter, dispatch_list))
    dispatch_group = groupby(dispatch_list, lambda x: x['Report'] + '_' + x['PDF-Schicht'])
    report_mails = {}
    for k, v in dispatch_group:
        report_mails[k] = '<br/>'.join([x['Empfaenger'] for x in v])

    template = jinja2.Template(html)
    mail_batch = []

    for group_name, v in groupby(dispatch_list, lambda x: x['Empfaenger']):
        group_filenames = []
        d_group = list(v)
        for row in d_group:
            ext = '.xls' if row['XLS'] == 'J' else '.pdf'
            filename = f"{publish_subdir}/{row['Report']}_{row['PDF-Schicht']}{ext}"

            row['Empfaenger'] = report_mails[row['Report'] + '_' + row['PDF-Schicht']]
            row['Dateiname'] = []
            row['Stand'] = 'nicht verf&uuml;gbar'
            row['Schicht'] = row['PDF-Schicht'] if row['PDF-Schicht'] != '0' else 'komplett'
            if Path(filename).exists():
                mtime = datetime.fromtimestamp(Path(filename).stat().st_mtime)
                row['Stand'] = mtime.strftime('%d.%m.%Y, %H:%M')
                if (datetime.now() - mtime).total_seconds() <= 60 * 60 * 12:
                    row['Dateiname'].append((row['Name'] + ext, filename))
                    group_filenames.append((row['Name'] + ext, filename))

            if cfg.versand_separat:
                mail_batch.append((group_name, row['Name'], template.render(reports=[row]), row['Dateiname']))

        if not cfg.versand_separat:
            mail_batch.append((group_name, 'GAPS-Versand', template.render(reports=d_group), group_filenames))
    return mail_batch


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


def main(xml_filename, recipient=None, report=None, cube=None):
    xml_filename = xml_filename.lower()
    if xml_filename[-4:] != '.xml':
        xml_filename = xml_filename + '.xml'

    mail_batch = dispatch(xml_filename, recipient, report, cube)
    for m in mail_batch:
        print(m[0])
    send_mail([mail_batch[0]])


if __name__ == '__main__':
    main('GAPS_Vers_Tag', 'robert.bedner@gmail.com')
