import traceback
from typing import Callable

from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import redirect, render

from vbv_lernwelt.importer.services import (
    import_course_sessions_from_excel,
    import_students_from_excel,
    import_trainers_from_excel_for_training,
    sync_students_from_t2l_excel,
)


@staff_member_required
def coursesessions_trainers_import(request):
    return handle_import(
        request,
        "Die Durchführungen und Trainer wurden erfolgreich importiert!",
        import_training_and_trainer,
    )


def import_training_and_trainer(excel_file: str):
    import_course_sessions_from_excel(
        excel_file,
        circle_keys=[
            "Kickoff",
            "Basis",
            "Fahrzeug",
            "Haushalt Teil 1",
            "Haushalt Teil 2",
        ],
    )
    import_trainers_from_excel_for_training(excel_file)


@staff_member_required
def coursesessions_students_import(request):
    return handle_import(
        request,
        "Die Teilnehmer wurden erflogreich importiert!",
        import_students_from_excel,
    )


@staff_member_required
def t2l_sync(request):
    return handle_import(
        request,
        "Die Daten wurden erflogreich synchronisiert!",
        sync_students_from_t2l_excel,
    )


def handle_import(request, success_msg: str, importer: Callable[[str], None]):
    if request.method == "POST" and request.FILES["excel_file"]:
        excel_file = request.FILES["excel_file"]
        try:
            importer(excel_file)
        except Exception as e:
            return render(
                # it is a "power" feature, so we will output the traceback on error
                request,
                "admin/importer/error.html",
                {"error": traceback.format_exc()},
            )

        messages.info(request, success_msg)
        return redirect("admin:index")
