package ru.ulstu.deadline.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.model.DeadlineDto;
import ru.ulstu.deadline.repository.DeadlineRepository;

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

@Service
public class DeadlineService {
    private final DeadlineRepository deadlineRepository;

    public DeadlineService(DeadlineRepository deadlineRepository) {
        this.deadlineRepository = deadlineRepository;
    }

    public List<Deadline> saveOrCreate(List<DeadlineDto> deadlines) {
        return deadlines.stream().map(deadlineDto -> {
            return deadlineDto.getId() != null ? update(deadlineDto) : create(deadlineDto);
        }).collect(Collectors.toList());
    }

    @Transactional
    public Deadline update(DeadlineDto deadlineDto) {
        Deadline deadline = deadlineRepository.findOne(deadlineDto.getId());
        deadlineRepository.save(copyFromDto(deadline, deadlineDto));
        return deadline;
    }

    @Transactional
    public Deadline create(DeadlineDto deadlineDto) {
        Deadline newDeadline = copyFromDto(new Deadline(), deadlineDto);
        newDeadline = deadlineRepository.save(newDeadline);
        return newDeadline;
    }

    private Deadline copyFromDto(Deadline deadline, DeadlineDto deadlineDto) {
        deadline.setDate(deadlineDto.getDate());
        deadline.setDescription(deadlineDto.getDescription());
        return deadline;
    }
}
