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.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<Deadline> deadlines) {
        return deadlines
                .stream()
                .map(deadline -> {
                    return deadline.getId() != null ? update(deadline) : create(deadline);
                }).collect(Collectors.toList());
    }

    @Transactional
    public Deadline update(Deadline deadline) {
        Deadline updateDeadline = deadlineRepository.findOne(deadline.getId());
        updateDeadline.setDate(deadline.getDate());
        updateDeadline.setDescription(deadline.getDescription());
        deadlineRepository.save(updateDeadline);
        return updateDeadline;
    }

    @Transactional
    public Deadline create(Deadline deadline) {
        Deadline newDeadline = new Deadline();
        newDeadline.setDate(deadline.getDate());
        newDeadline.setDescription(deadline.getDescription());
        newDeadline = deadlineRepository.save(newDeadline);
        return newDeadline;
    }
}
