package org.fuseri.modulelanguageschool.lecture;

import org.fuseri.model.dto.lecture.LectureCreateDto;
import org.fuseri.model.dto.lecture.LectureDto;
import org.fuseri.modulelanguageschool.course.CourseService;
import org.fuseri.modulelanguageschool.user.User;
import org.fuseri.modulelanguageschool.user.UserService;
import org.mapstruct.Mapper;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Mapper(componentModel = "spring", uses = {UserService.class})
public interface LectureMapper {

    default LectureDto mapToDto(Lecture lecture) {
        if (lecture == null) {
            return null;
        }

        var dto = new LectureDto(lecture.getLectureFrom(),
                lecture.getLectureTo(),
                lecture.getTopic(),
                lecture.getCapacity(),
                lecture.getLecturer() == null ? null : lecture.getLecturer().getId(),
                lecture.getCourse().getId(),
                new ArrayList<>(lecture.getStudents().stream().map(User::getId).collect(Collectors.toList())));
        dto.setId(lecture.getId());
        return dto;
    }

    default Lecture mapToLecture(LectureDto lectureDto, CourseService courseService, UserService userService) {
        if (lectureDto == null) {
            return null;
        }
        var lecture = new Lecture(lectureDto.getLectureFrom(),
                lectureDto.getLectureTo(),
                lectureDto.getTopic(),
                lectureDto.getCapacity(),
                courseService.findById(lectureDto.getCourseId()),
                userService.find(lectureDto.getLecturerId()),
                new ArrayList<>());
        lecture.setId(lectureDto.getId());
        for (Long userId : lectureDto.getStudents()) {
            lecture.enrolStudent(userService.find(userId));
        }
        return lecture;
    }

    default List<LectureDto> mapToList(List<Lecture> lectures) {
        if (lectures == null) {
            return null;
        }
        return new ArrayList<>(lectures.stream().map(this::mapToDto).toList());
    }


    default Lecture mapToLecture(LectureCreateDto lectureDto, CourseService courseService) {
        if (lectureDto == null) {
            return null;
        }
        return new Lecture(lectureDto.getLectureFrom(),
                lectureDto.getLectureTo(),
                lectureDto.getTopic(),
                lectureDto.getCapacity(),
                courseService.findById(lectureDto.getCourseId()),
                null,
                new ArrayList<>());
    }
}
