import os

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_trainer
from vbv_lernwelt.importer.utils import calc_header_tuple_list_from_pyxl_sheet

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


class ImportTrainerTestCase(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",
        )
        self.course_session_a = CourseSession.objects.create(
            course=self.course,
            title="Deutschschweiz 2023 B",
            import_id="DE 2023 B",
            group="B",
        )

    def test_import_excel_file(self):
        workbook = load_workbook(
            filename=f"{test_dir}/Schulungen_Durchfuehrung_Trainer.xlsx"
        )
        sheet = workbook["Schulungen Trainer"]

        tuple_list = calc_header_tuple_list_from_pyxl_sheet(sheet)
        for row in tuple_list:
            print(row)
            create_or_update_trainer(self.course, dict(row))

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


class CreateOrUpdateTrainerTestCase(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",
        )
        self.course_session_a = CourseSession.objects.create(
            course=self.course,
            title="Deutschschweiz 2023 B",
            import_id="DE 2023 B",
            group="B",
        )

    def test_create_trainer(self):
        row = [
            ("Name", "Hänni"),
            ("Vorname", "Fabienne"),
            ("Email", "fabienne.haenni@vbv-afa.ch"),
            ("Sprache", "de"),
            ("Generation", "DE 2023"),
            ("Klasse", "A, B"),
            ("Circles", "Fahrzeug (A, B), Reisen (A), KMU (B)"),
            ("Status Referenten", "ok"),
            (None, "Schulung D"),
        ]

        create_or_update_trainer(self.course, dict(row))

        self.assertEqual(
            CourseSessionUser.objects.filter(
                user__email="fabienne.haenni@vbv-afa.ch"
            ).count(),
            2,
        )

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

        self.assertEqual(csu.role, CourseSessionUser.Role.EXPERT)
        self.assertEqual(csu.user.email, "fabienne.haenni@vbv-afa.ch")
        self.assertEqual(csu.expert.all().first().title, "Fahrzeug")
