package ru.ulstu.paper.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.repository.PaperRepository;
import ru.ulstu.user.model.User;
import ru.ulstu.user.scheduler.UserScheduler;
import ru.ulstu.user.service.MailService;

import java.util.Calendar;
import java.util.List;

@Service
public class DeadlineScheduler {

    private final Logger log = LoggerFactory.getLogger(DeadlineScheduler.class);

    private final PaperRepository paperRepository;

    private final MailService mailService;

    private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true;

    public DeadlineScheduler(PaperRepository paperRepository, MailService mailService) {
        this.paperRepository = paperRepository;
        this.mailService = mailService;
    }


    @Scheduled(cron = "0 0 8 * 1 ?")
    public void checkDeadlineBeforeWeek() {
        log.debug("DeadlineScheduler.checkDeadlineBeforeWeek started");
        sendNotifications(IS_DEADLINE_NOTIFICATION_BEFORE_WEEK);
        log.debug("DeadlineScheduler.checkDeadlineBeforeWeek finished");
    }

    @Scheduled(cron = "0 0 8 * * ?")
    public void checkDeadlineAfterWeek() {
        log.debug("DeadlineScheduler.checkDeadlineAfterWeek started");
        sendNotifications(!IS_DEADLINE_NOTIFICATION_BEFORE_WEEK);
        log.debug("DeadlineScheduler.checkDeadlineAfterWeek finished");
    }

    private void sendNotifications(boolean isDeadlineBeforeWeek) {
        List<Paper> allPapers = paperRepository.findAll();
        for (Paper paper : allPapers) {
            Calendar c = Calendar.getInstance();
            c.add(Calendar.DAY_OF_YEAR, 7);
            if (((c.getTime().compareTo(paper.getDeadlineDate()) < 0) && isDeadlineBeforeWeek) ||
                    (c.getTime().compareTo(paper.getDeadlineDate()) >= 0) && !isDeadlineBeforeWeek) {
                sendMessageDeadline(paper);
            }
        }
    }

    private void sendMessageDeadline(Paper paper){
        for (User user : paper.getAuthors()) {
            mailService.sendEmail(user.getEmail(), "Приближается срок сдачи статьи",
                    "Срок сдачи статьи " + paper.getTitle() + " " + paper.getDeadlineDate().toString());
        }
    }
}
