package eu.dnetlib.lbs.cron;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import eu.dnetlib.lbs.elasticsearch.EventRepository;
import eu.dnetlib.lbs.elasticsearch.NotificationRepository;
import eu.dnetlib.lbs.matchers.SubscriptionEventMatcher;
import eu.dnetlib.lbs.subscriptions.SubscriptionRepository;

@Component
public class ScheduledActions {

	@Autowired
	private EventRepository eventRepository;

	@Autowired
	private NotificationRepository notificationRepository;

	@Autowired
	private SubscriptionRepository subscriptionRepo;

	@Autowired
	private SubscriptionEventMatcher subscriptionEventMatcher;

	private static final Log log = LogFactory.getLog(ScheduledActions.class);

	@Scheduled(cron = "${lbs.task.deleteOldEvents.cron}")
	public long deleteExpiredEvents() {
		// TODO : the date used in the query should be the min among the dates of the subscriptions (considering only the subscriptions with
		// creation_date > events.creationDate)

		final long n = this.eventRepository.deleteByExpiryDateBefore(new Date().getTime());
		log.info("Number of deleted expired events: " + n);
		return n;
	}

	@Scheduled(cron = "${lbs.task.deleteOldNotifications.cron}")
	public long deleteExpiredNotifications() {
		// TODO

		return 0;
	}

	@Scheduled(cron = "${lbs.task.subscriptionEventsMatcher.cron}")
	public void startSubscriptionEventsMatcher() {
		this.subscriptionRepo.findAll().forEach(this.subscriptionEventMatcher::startMatching);
	}

}
