from io import BytesIO
import unittest

import numpy as np
import pandas as pd
from backend import his_io


class TestHisio(unittest.TestCase):

    def check_students_table(self, table):
        self.assertEqual(table.shape, (6, 20))
        self.assertEqual(list(table.columns), 
                         ['Examplan.id', 'PrüfungsNr.', 'Titel', 'Nachname', 'Vorname', 'Leistung', 'Versuch',
                          'Status', 'ECTS', 'Semester', 'Jahr', 'Prüfungsperiode', 'Vermerk', 'Thema', 'Beginn',
                          'Gepl. Ende', 'Tatsächl. Ende', 'Prüfungsart', 'Prüfungsform', 'LockVersion'])
        
        self.assertEqual(table.index.name, 'Matrikelnummer')
        self.assertEqual(list(table.index), [3434343, 3535353, 3131313, 2323232, 3737373, 3939393])
        self.assertEqual(list(table['Examplan.id']), [1414141, 1515151, 1111111, 1313131, 1717171, 1919191])
        self.assertEqual(list(table['Nachname']), ['Hendrix', 'Lukather', 'Mayer', 'Page', 'Townshend', 'Van Halen'])
        self.assertEqual(list(table['LockVersion']), [
            'ea56ef45-1b42-4a9f-8dc2-e9f3b8e6c9a1=0,109aefbb-988c-44a8-a72d-82ad0025dcb0=0,6aed40c3-8ca7-4cf8-8004-534c11121a43=0,',
            '1e851fa6-6f69-4fe4-a1a8-510ab8e5c6ea=0,eeecd36a-ee4a-4897-b7db-464542618fb3=0,3fda53aa-2106-4f8b-a832-03aa57917cb2=0,',
            'fd952c3a-c789-4af2-88fd-0dbe8ea0e68b=0,5a639ec2-eec4-4d53-bd92-5ed368f164c3=0,26270d08-a83b-4c2a-94e3-fc732553ef99=0,',
            'ee3f3068-dad7-489c-a5e7-f2eccaedacf7=0,92e970b1-d447-4009-8dde-676d6a31a337=0,8c29a40c-8aa1-4585-b77b-78b410e3d12d=0,',
            '1832c736-1d8c-4d49-bdcd-4295fc5bf3b4=0,8f5bf01d-9cc3-4bb9-86c1-c6d5d0cbc45a=0,9c9cce83-7a96-47fb-acdd-8fc0fd5fddfa=0,',
            '14d1b781-a879-4115-a444-c87b725bbfe2=0,98e734b2-3253-43c2-a173-2fe7e686bc93=0,cb6d9ca0-b3e5-40c9-b7f9-e6e3e4511e50=0,'])
        self.assertEqual(dict(table.dtypes), his_io.dtypes.students_table)

    def check_header(self, header):
        self.assertEqual(header.shape, (4, 21))
        self.assertEqual(list(header[0]), ['5160 - Rocket Science (Prüfung) | Prüfer/-in: Schröder, Enrico | Wintersemester 2023/24 | Prüfungsperiode 1', None, 'EXAM_CHECK_TOKEN', 'startHISsheet'])
        self.assertEqual(header.iloc[2, 1], '6711e6e8b09fe054d0216a4745b5c56d')

    def test(self):
        with open('5160-RocketScience-WiSe_2023.xlsx', 'rb') as f:
            self.table_bytes = BytesIO(f.read())

        students_table, his_header = None, None
        with self.subTest('read'):
            students_table, his_header = his_io.read_excel(self.table_bytes)
            self.assertIsNotNone(students_table)
            self.assertIsNotNone(his_header)

        
        with self.subTest('students_table'):
            self.check_students_table(students_table)
            self.assertTrue(students_table['Leistung'].isna().all())

        with self.subTest('his_header'):
            self.check_header(his_header)

        with self.subTest('prepare_table'):
            points_table = his_io.prepare_table(students_table)
            self.assertEqual(points_table.shape, (6, 22))
            self.assertEqual(list(points_table.columns), 
                             ['Examplan.id', 'PrüfungsNr.', 'Titel', 'Nachname', 'Vorname', 'Leistung', 'Versuch',
                              'Status', 'ECTS', 'Semester', 'Jahr', 'Prüfungsperiode', 'Vermerk', 'Thema', 'Beginn',
                              'Gepl. Ende', 'Tatsächl. Ende', 'Prüfungsart', 'Prüfungsform', 'LockVersion', 'Punkte', 'Note'])
            self.assertTrue(points_table['Punkte'].isna().all())
            self.assertTrue(points_table['Note'].isna().all())

        with self.subTest('export'):
            points_table['1'] = [1, 2, 3, 4, 5, 0]
            points_table['2'] = [0, 1, 2, 3, 4, 5]
            points_table['Punkte'] = [1, 2, 3, 4, 5, 6]
            points_table['Note'] = ['1,0', '2,0', '3,0', '4,0', '5,0', 'NT']
            grades_table = pd.DataFrame({'Note': ['1,0', '2,0', '3,0', '4,0', '5,0', 'NT'], 
                                         'Prozent': [0.9, 0.8, 0.6, 0.4, 0.2, 0.1],
                                         'Untergrenze': [100, 80, 60, 40, 20, 0],
                                         'Obergrenze': [100, 80, 60, 40, 20, 0]})
            
            export_bytes = his_io.export(points_table, his_header, ['1', '2'], grades_table)
            self.assertIsNotNone(export_bytes)

            exported_students_table, exported_his_header = his_io.read_excel(export_bytes)
            self.check_students_table(exported_students_table)
            self.assertEqual(list(exported_students_table['Leistung']), ['1,0', '2,0', '3,0', '4,0', '5,0', 'NT'])
            self.check_header(exported_his_header)

        with self.subTest('exported_summary'):
            summary_sheet = pd.read_excel(export_bytes, header=None, sheet_name='Aufgaben')
            self.assertIsNotNone(summary_sheet)
            self.assertEqual(summary_sheet.shape, (7, 7))
            self.assertEqual(list(summary_sheet.iloc[0]), ['Matrikelnummer', 'Nachname', 'Vorname', 'Punkte', 'Note', 1, 2])
            self.assertEqual(list(summary_sheet.iloc[1]), [3434343, 'Hendrix', 'Jimi', 1, '1,0', 1, 0])
            self.assertEqual(list(summary_sheet.iloc[6]), [3939393, 'Van Halen', 'Eddie', 6, 'NT', 0, 5])

        with self.subTest('exported_grades_table'):
            grades_table = pd.read_excel(export_bytes, header=None, sheet_name='Notenschlüssel')
            self.assertIsNotNone(grades_table)
            self.assertEqual(grades_table.shape, (6, 4))
            self.assertEqual(list(grades_table.iloc[2]), ['3,0', 0.6, 60, 60])


if __name__ == '__main__':
    unittest.main()