from students.models import Student
from classes.models import Class
from subjects.models import Subject
from courses.models import Course
from api.utils import json_to_data


def store_students(path):
    """
    Gets students data from students.json (generated by web scraping)
    and instantiates Student objects in the database
    """
    students_data = json_to_data(path)
    students = students_data["students"]
    for student in students:
        try:
            student_instance = Student.objects.get(ra=student["ra"])
        # if student instance doesn't exist already
        except:
            if student["course"] != "0":
                course_instance = Course.objects.get(id=int(student["course"]))
                student_instance = Student.objects.create(
                    ra=student["ra"],
                    name=student["name"],
                    course=course_instance)
            # course == "0" is a special case in which the student has
            # entered in college by a non traditional way
            else:
                student_instance = Student.objects.create(ra=student["ra"],
                                                          name=student["name"])
        for _class in student["classes"]:
            subject_instance = Subject.objects.get(initials=_class["subject"])
            class_instance = subject_instance.class_set.get(
                class_id=_class["class"])
            student_instance.classes.add(class_instance)


def run():
    store_students("students/students.json")
