package ru.ulstu.timeline.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.timeline.model.EventDto;
import ru.ulstu.timeline.model.Timeline;
import ru.ulstu.timeline.model.TimelineDto;
import ru.ulstu.timeline.repository.TimelineRepository;

import java.util.List;

import static ru.ulstu.core.util.StreamApiUtils.convert;

@Service
public class TimelineService {

    private final TimelineRepository timelineRepository;
    private final EventService eventService;

    public TimelineService(TimelineRepository timelineRepository,
                           EventService eventService) {
        this.timelineRepository = timelineRepository;
        this.eventService = eventService;
    }

    public List<TimelineDto> findAll() {
        return convert(timelineRepository.findAll(), TimelineDto::new);
    }

    @Transactional
    public int create(TimelineDto timelineDto) {
        return timelineRepository.save(copyFromDto(new Timeline(), timelineDto)).getId();
    }

    private Timeline copyFromDto(Timeline timeline, TimelineDto timelineDto) {
        timeline.setEvents(eventService.findByIds(convert(timelineDto.getEvents(), EventDto::getId)));
        return timeline;
    }

    @Transactional
    public Integer update(TimelineDto timelineDto) {
        Timeline timeline = timelineRepository.findOne(timelineDto.getId());
        return timelineRepository.save(copyFromDto(timeline, timelineDto)).getId();
    }

    @Transactional
    public void delete(Integer timelineId) {
        Timeline timeline = timelineRepository.findOne(timelineId);
        timelineRepository.delete(timeline);
    }
}
