package ru.ulstu.timeline.service;

import com.google.common.collect.ImmutableMap;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.timeline.model.EventDto;
import ru.ulstu.timeline.repository.EventRepository;
import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.service.MailService;
import ru.ulstu.user.service.UserService;

import java.util.List;
import java.util.Map;

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

@Service
public class EventService {

    private final EventRepository eventRepository;
    private final UserService userService;
    private final MailService mailService;

    public EventService(EventRepository eventRepository,
                        UserService userService,
                        MailService mailService) {
        this.eventRepository = eventRepository;
        this.userService = userService;
        this.mailService = mailService;
    }

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

    @Transactional
    public int create(EventDto eventDto) {
        return eventRepository.save(copyFromDto(new Event(), eventDto)).getId();
    }

    private Event copyFromDto(Event event, EventDto eventDto) {
        event.setExecuteDate(eventDto.getExecuteDate());
        event.setCreateDate(eventDto.getCreateDate());
        event.setDescription(eventDto.getDescription());
        event.setRecipients(userService.findByIds(convert(eventDto.getRecipients(), UserDto::getId)));
        event.setTitle(eventDto.getTitle());
        event.setStatus(eventDto.getStatus());
        event.setUpdateDate(eventDto.getUpdateDate());
        return event;
    }

    @Transactional
    public Integer update(EventDto eventDto) {
        Event event = eventRepository.findOne(eventDto.getId());
        return eventRepository.save(copyFromDto(event, eventDto)).getId();
    }

    @Transactional
    public void delete(Integer timelineId) {
        Event event = eventRepository.findOne(timelineId);
        eventRepository.delete(event);
    }

    public List<Event> findByIds(List<Integer> ids) {
        return eventRepository.findAll(ids);
    }

    @Scheduled(cron = "0 0 8 * * ?")
    public void sendNotifications() {
        List<Event> events = eventRepository.findByCurrentDate();
        events.forEach(event -> {
            Map<String, Object> variables = ImmutableMap.of("description", event.getDescription());
            event.getRecipients()
                    .forEach(recipient -> mailService.sendEmailFromTemplate(variables, recipient, "eventNotification", event.getTitle()));
        });
    }
}
