import os
from datetime import datetime

from django.test import TestCase
from openpyxl.reader.excel import load_workbook

from vbv_lernwelt.course.creators.test_course import create_test_course
from vbv_lernwelt.course.models import CourseSession, CourseSessionUser
from vbv_lernwelt.importer.services import create_or_update_student
from vbv_lernwelt.importer.utils import calc_header_tuple_list_from_pyxl_sheet

test_dir = os.path.dirname(os.path.abspath(__file__))


class ImportStudentsTestCase(TestCase):
    def setUp(self):
        self.course = create_test_course(include_vv=False)
        self.course_session_a = CourseSession.objects.create(
            course=self.course,
            title="Deutschschweiz 2023 A",
            import_id="DE 2023 A",
            group="A",
        )

    def test_import_excel_file(self):
        workbook = load_workbook(filename=f"{test_dir}/Schulungen_Teilnehmende.xlsx")
        sheet = workbook.active

        tuple_list = calc_header_tuple_list_from_pyxl_sheet(sheet)
        for row in tuple_list:
            print(row)
            create_or_update_student(dict(row))

        self.assertEqual(CourseSessionUser.objects.count(), 14)


class CreateOrUpdateStudentTestCase(TestCase):
    def setUp(self):
        self.course = create_test_course(include_vv=False)
        self.course_session_a = CourseSession.objects.create(
            course=self.course,
            title="Deutschschweiz 2023 A",
            import_id="DE 2023 A",
            group="A",
        )

    def test_create_student(self):
        row = [
            ("Name", "Rascher"),
            ("Vorname", "Barbara"),
            ("Email", "barbara.rascher@vbv-afa.ch"),
            ("Sprache", "de"),
            ("Durchführungen", "DE 2023 A"),
            ("Datum", datetime(2023, 9, 6, 0, 0)),
            (None, "VBV"),
            (None, None),
            (None, None),
            (None, None),
            (None, None),
        ]

        create_or_update_student(dict(row))

        self.assertEqual(
            CourseSessionUser.objects.filter(
                user__email="barbara.rascher@vbv-afa.ch"
            ).count(),
            1,
        )

        csu = CourseSessionUser.objects.get(
            course_session=self.course_session_a,
        )

        self.assertEqual(csu.role, CourseSessionUser.Role.MEMBER)
        self.assertEqual(csu.user.email, "barbara.rascher@vbv-afa.ch")
