package ovh.herisson.Clyde.Services;

import org.springframework.stereotype.Controller;
import ovh.herisson.Clyde.Repositories.TeacherCourseRepository;
import ovh.herisson.Clyde.Repositories.UserRepository;
import ovh.herisson.Clyde.Tables.Course;
import ovh.herisson.Clyde.Tables.Role;
import ovh.herisson.Clyde.Tables.TeacherCourse;
import ovh.herisson.Clyde.Tables.User;

import java.util.ArrayList;

@Controller
public class TeacherCourseService {
    private final TeacherCourseRepository teacherCourseRepo;

    private final UserRepository userRepo;

    public TeacherCourseService(TeacherCourseRepository teacherCourseRepo, UserRepository userRepo) {
        this.teacherCourseRepo = teacherCourseRepo;
        this.userRepo = userRepo;
    }

    public Iterable<User> findCourseAssistants(Course course) {
        if (course == null)
            return null;
        return teacherCourseRepo.findAllAssistantOfCourse(course);
    }


    public boolean saveAll(Iterable<Long> teacherIds, Course course){

        if (course == null  || teacherIds == null)
            return false;

        ArrayList<User> toAdd = new ArrayList<>();
        for (Long teacherId : teacherIds){
            User teacher = userRepo.findById((long) teacherId);
            if ( teacher== null){
                return false;
            }
            if (!toAdd.contains(teacher) && teacher.getRole() == Role.Teacher)
            {
                toAdd.add(teacher);
            }
        }
        for (User teacher: toAdd){
            teacherCourseRepo.save(new TeacherCourse(teacher,course));
        }
        return true;
    }

}
