package eu.dnetlib.broker.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.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import eu.dnetlib.broker.common.elasticsearch.EventRepository;
import eu.dnetlib.broker.common.subscriptions.SubscriptionRepository;
import eu.dnetlib.broker.matchers.SubscriptionEventMatcher;

@Component
@Profile("!openaire")
public class ScheduledActions {

	@Autowired
	private EventRepository eventRepository;

	@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() {
		final long n = this.eventRepository.deleteByExpiryDateBetween(0, new Date().getTime());
		log.info("Number of deleted expired events: " + n);
		return n;
	}

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

}
