import json
from src.domain.student import Student
from src.errors.errors import *

class StudentsRepo():
    """
    Class for the repository of students
    Reads and writes from a json file
    Attributes:
        __path: the path to the json file
        students: a list of students
    Methods:
        __load_from_file: loads the students from the json file
        __save_to_file: saves the students to the json file
        add_student: adds a student to the repository
        remove_student: removes a student from the repository
        update_student: updates a student from the repository
        list_students: returns a list of students
        is_a_student: returns True if the student is in the repository
    """
    def __init__(self,path:str) -> None:
        self.__path = path
        self.students = []
        self.__load_from_file()
    
    def __load_from_file(self) -> None:
        with open(self.__path,"r") as f:
            students = json.load(f)
            for student in students:
                self.students.append(Student(student["student_id"],student["name"],student["group"]))
       
    def __save_to_file(self) -> None:
        students = []
        for student in self.students:
            students.append(student.toJson())
        with open(self.__path,"w") as f:
            json.dump(students,f,indent=4)

    def add_student(self, student: Student) -> None:
        if student.get_student_id() in [student.get_student_id() for student in self.students]:
            raise StudentAlreadyExistsError("Student already exists")
        self.students.append(student)
        self.__save_to_file()


    def remove_student(self, student_id: str) -> None:
        for student in self.students:
            if student.get_student_id() == student_id:
                self.students.remove(student)
                self.__save_to_file()
                return
        raise StudentNotFoundError("Student not found")


    def update_student(self, student: Student) -> None:
        for student_in_list in self.students:
            if student_in_list.get_student_id() == student.get_student_id():
                student_in_list.set_name(student.get_name())
                student_in_list.set_group(student.get_group())
                self.__save_to_file()
                return
        raise StudentNotFoundError("Student not found")

    def list_students(self) -> list[Student]:
        return self.students
    
    def is_a_student(self,student_id:str) -> bool:
        for student in self.students:
            if student.get_student_id() == student_id:
                return True
        return False
    


