import datetime

from django.conf import settings

from .models import Lock, StudentsA, StudentsB, \
    Stumodules, TimetableA, TimetableB, \
    WeekmapnumericA, WeekmapnumericB, \
    WeekstructureA, WeekstructureB

_SETID = settings.ROOMBOOKINGS_SETID

_week_map = {}
_week_num_date_map = {}


def _get_cache(model_name):
    models = {
        "students": [StudentsA, StudentsB],
        "timetable": [TimetableA, TimetableB],
        "weekmapnumeric": [WeekmapnumericA, WeekmapnumericB],
        "weekstructure": [WeekstructureA, WeekstructureB]
    }
    lock = Lock.objects.all()[0]
    model = models[model_name][0] if lock.a else models[model_name][1]
    return model


def _get_student_by_upi(upi):
    print("Getting student by UPI: " + upi)
    students = _get_cache("students")
    # Assume the current Set ID due to caching
    upi_upper = upi.upper()
    student = students.objects.filter(
        qtype2=upi_upper
    )[0]
    print("Got student")
    return student


def _get_student_modules(student):
    print("Getting student modules for student: " + student.qtype2)
    # student_modules = list(Stumodules.objects.filter(
    #     studentid=student.studentid,
    #     setid=_SETID
    # ))
    raw_query = 'SELECT * FROM CMIS_OWNER.STUMODULES WHERE SETID=\'LIVE-17-18\' AND studentid=\'{}\''.format(
        student.studentid
    )
    student_modules = list(Stumodules.objects.raw(raw_query))
    print("Got student modules for student: " + student.qtype2)
    return student_modules


def _get_timetable_events(student_modules):
    print("Getting timetabled events")
    if not _week_map:
        _map_weeks()

    timetable = _get_cache("timetable")
    student_timetable = []
    for module in student_modules:
        print("Getting data for Module ID " + module.moduleid)
        events_data = timetable.objects.filter(
            moduleid=module.moduleid,
            modgrpcode=module.modgrpcode
        )
        events = []
        for event in events_data:
            for date in _get_real_dates(event["slotid"]):
                events += {
                    "starttime": event["starttime"],
                    "endtime": event["finishtime"],
                    "duration": event["duration"],
                    "lecturerid": event["lecturerid"],
                    "moduletype": event["moduletype"],
                    "modgrpcode": event["modgrpcode"],
                    "siteid": event["siteid"],
                    "roomid": event["roomid"],
                    "startdate": date,
                    "moduleid": event["moduleid"],
                    "modulegroup": module["modgrpcode"]
                }
        student_timetable += events
    print("Got timetabled events")
    return student_modules


def _map_weeks():
    print("Mapping weeks")
    weekmapnumeric = _get_cache("weekmapnumeric")
    weekstructure = _get_cache("weekstructure")
    week_nums = weekmapnumeric.objects.all()
    week_strs = weekstructure.objects.all()

    for week in week_strs:
        _week_num_date_map[week.weeknumber] = week.startdate

    for week in week_nums:
        if week.weekid not in _week_map:
            _week_map[week.weekid] = []
        _week_map[week.weekid].append(week.weeknumber)
    print("Weeks mapped successfully")


def _get_real_dates(slot):
    return [
        _week_num_date_map[startdate] + datetime.timedelta(
            days=slot.weekday - 1
        )
        for startdate in _week_map[slot.weekid]
    ]


def get_student_timetable(upi):
    print("*** GETTING STUDENT TIMETABLE FOR UPI " + upi + " ***")
    student = _get_student_by_upi(upi)
    print("Getting modules....")
    student_modules = _get_student_modules(student)
    print("Getting events...")
    student_events = _get_timetable_events(student_modules)
    print("Returning events...")
    return student_events

@@ -2107,17 +2107,15 @@
 vent
-%5B%22
+.
 slotid
-%22
 %5D):%0D
@@ -2182,18 +2182,17 @@
 %22: event
-%5B%22
+.
 starttim
@@ -2188,26 +2188,24 @@
 nt.starttime
-%22%5D
 ,%0D%0A         
@@ -2231,18 +2231,17 @@
 %22: event
-%5B%22
+.
 finishti
@@ -2242,18 +2242,16 @@
 nishtime
-%22%5D
 ,%0D%0A     
@@ -2286,18 +2286,17 @@
 vent
-%5B%22
+.
 duration
 %22%5D,%0D
@@ -2291,18 +2291,16 @@
 duration
-%22%5D
 ,%0D%0A     
@@ -2333,18 +2333,17 @@
 %22: event
-%5B%22
+.
 lecturer
@@ -2344,18 +2344,16 @@
 cturerid
-%22%5D
 ,%0D%0A     
@@ -2382,26 +2382,25 @@
 type%22: event
-%5B%22
+.
 moduletype%22%5D
@@ -2397,18 +2397,16 @@
 duletype
-%22%5D
 ,%0D%0A     
@@ -2439,18 +2439,17 @@
 %22: event
-%5B%22
+.
 modgrpco
@@ -2450,18 +2450,16 @@
 dgrpcode
-%22%5D
 ,%0D%0A     
@@ -2492,18 +2492,15 @@
 vent
-%5B%22
+.
 siteid
-%22%5D
 ,%0D%0A 
@@ -2537,18 +2537,15 @@
 vent
-%5B%22
+.
 roomid
-%22%5D
 ,%0D%0A 
@@ -2624,18 +2624,17 @@
 vent
-%5B%22
+.
 moduleid
 %22%5D,%0D
@@ -2629,18 +2629,16 @@
 moduleid
-%22%5D
 ,%0D%0A     
@@ -2677,10 +2677,9 @@
 dule
-%5B%22
+.
 modg
@@ -2688,10 +2688,8 @@
 code
-%22%5D
 %0D%0A  

Remove subscripting