from Repository.Loader import Loader, LoaderException
from Domain import Grade, Student, Discipline

import json


class JsonLoader(Loader):
    def save(self):
        # serializable = {'students': [], 'disciplines': [], 'grades': []}
        serializable = {
            'students': [{'id': student.getId(), 'name': student.getName()} for student in self.repo.getStudents()],
            'disciplines': [{'id': discipline.getId(), 'name': discipline.getName()} for discipline in
                            self.repo.getDisciplines()],
            'grades': [{'did': grade.getDisciplineId(), 'sid': grade.getStudentId(), 'grade': grade.getGrade()} for grade in
                       self.repo.getGrades()]}

        try:
            with open(self.repo.getStoragePath() + ".json", "w") as f:
                json.dump(serializable, f, indent=4)
            return True
        except IOError:
            # Raise exception because not being able to save is worse than not being able to load
            raise LoaderException("Failed pickling current database.")

    def load(self):
        try:
            with open(self.repo.getStoragePath() + ".json", "r") as f:
                self.repo._createNewRepo()
                jsonHistory = json.load(f)
                if 'students' in jsonHistory.keys():
                    for serializedStudent in jsonHistory['students']:
                        self.repo.addStudent(Student.Student(serializedStudent['id'], serializedStudent['name']), False)
                if 'disciplines' in jsonHistory.keys():
                    for serializedDiscipline in jsonHistory['disciplines']:
                        self.repo.addDiscipline(Discipline.Discipline(serializedDiscipline['id'], serializedDiscipline['name']), False)
                if 'grades' in jsonHistory.keys():
                    for serializedGrade in jsonHistory['grades']:
                        self.repo.addGrade(Grade.Grade(serializedGrade['did'], serializedGrade['sid'], serializedGrade['grade']), False)
                return True
        except IOError as ex:
            print('[StudentRepository]', ex)
            return False

# eval studentCatalogController._repo._converter(0)
