#!/usr/bin/env python3
import csv
import datetime
import os
import sys
import tempfile
from operator import itemgetter

from fillpdf import fillpdfs
from pdfrw import PdfReader, PdfWriter

# Change to your needs
start_date = "2025-10-29"
end_date = "2025-11-02"
event_org = "Verein der Freunde und Förderer der Bundesfachschaftentagung Elektrotechnik e.V."
event_name = "97. Bundesfachschaftentagung Elektrotechnik"
attendees_csv = "97_teilnehmer.csv"
empty_sheets = 1
template_form = "Teilnehmendenliste_FR_22_23_final.pdf"

# Nothing to change below here

start = datetime.date.fromisoformat(start_date)
end = datetime.date.fromisoformat(end_date)
event_period = f'{start.strftime("%d.%m.%y")} - {end.strftime("%d.%m.%y")}'
days = int((end - start).days)
date_list = [(start + datetime.timedelta(days=i)).strftime('%d.%m.%y') for i in range(days + 1)]

form_mapping = [("6", "20", "21"), ("19", "40", "41"), ("18", "39", "22"),
                ("17", "42", "23"), ("16", "43", "24"), ("15", "44", "25"), ("14", "45", "26"),
                ("13", "46", "27"), ("12", "Text7", "28"), ("11", "29", "34"), ("10", "30", "35"),
                ("9", "31", "36"), ("8", "32", "37"), ("7", "33", "38")]


def read_csv(csv_path):
    try:
        csvfile = open(csv_path, newline='', encoding='utf-8')
    except FileNotFoundError:
        print("[X] File {} not found!".format(csv_path))
        sys.exit(1)
    else:
        with csvfile:
            reader = csv.DictReader(csvfile, delimiter=",")
            persons = [{"Name": f"{t['Amtlicher Vorname'] if t['Amtlicher Vorname'] else t['Vorname']} {t['Nachname']}", "Hochschule": f"{t['Standort']}"} for t in reader if
                       t['Status'] == "Immatrikuliert"]
            persons.sort(key=itemgetter("Hochschule", "Name"))

    return persons


def fill_template(template_path, persons_list, headers, output_path, start_index=1):
    fields = {}

    for idx, (person, mapping) in enumerate(zip(persons_list, form_mapping), start=start_index):
        fields[mapping[0]] = str(idx)
        fields[mapping[1]] = person["Name"]
        fields[mapping[2]] = person["Hochschule"]

    fields = {**headers, **fields}

    fillpdfs.write_fillable_pdf(input_pdf_path=template_path, output_pdf_path=output_path, data_dict=fields,
                                flatten=False)



def create_pdf(output_pdf, form, persons_chunks, zeitraum, form_date, org_name, name, add_sheets):
    page = 1
    output_file_name = "output"

    writer = PdfWriter()
    form_reader = PdfReader(template_form)
    writer.trailer.Info = form_reader.Info

    person_index = 1  # Fortlaufende Nummerierung über alle Seiten
    with tempfile.TemporaryDirectory() as workdir:
        for persons_list in persons_chunks + [[] for i in range(add_sheets)]:
            output_file_path = os.path.join(workdir, f'{output_file_name}{page}.pdf')
            headers = {"1": page, "2": zeitraum, "3": form_date, "4": org_name, "5": name}
            fill_template(template_path=form, persons_list=persons_list, headers=headers, output_path=output_file_path, start_index=person_index)
            person_index += len(persons_list)  # Erhöhe den Index für die nächste Seite
            reader = PdfReader(output_file_path)
            writer.addpages(reader.pages)
            page += 1

        writer.write(output_pdf)


if __name__ == "__main__":
    cwd = os.getcwd()
    csv_file_path = os.path.join(cwd, attendees_csv)
    form_path = os.path.join(cwd, template_form)

    # check if form exits
    if not os.path.exists(form_path):
        print("[X] File {} not found!".format(form_path))
        sys.exit(1)

    person_list = read_csv(csv_file_path)
    if not person_list:
        print("CSV file was empty")
        sys.exit(0)
    persons_per_page = len(form_mapping)

    person_list_per_page = [person_list[i:i + persons_per_page] for i in range(0, len(person_list), persons_per_page)]

    generated_files = []
    for date in date_list:
        final_pdf_name = f'teilnehmendenliste_{date.replace(".", "_").replace(" ", "")}.pdf'
        generated_files.append(final_pdf_name)
        final_pdf_path = os.path.join(cwd, final_pdf_name)
        print(f'Creating {final_pdf_name}... ', end='')
        create_pdf(final_pdf_path, form_path, person_list_per_page, event_period, date, event_org, event_name, empty_sheets)
        print('done!')
