package eu.eudat.logic.utilities.schedule.notification;

import eu.eudat.data.entities.Notification;
import eu.eudat.data.enumeration.notification.ActiveStatus;
import eu.eudat.data.enumeration.notification.NotifyState;
import eu.eudat.logic.managers.NotificationManager;
import eu.eudat.logic.services.ApiContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Component
public class NotificationScheduleJob {
	private static final Logger logger = LoggerFactory.getLogger(NotificationScheduleJob.class);

	private ApiContext apiContext;
	private NotificationManager notificationManager;

	@Autowired
	public NotificationScheduleJob(ApiContext apiContext, NotificationManager notificationManager) {
		this.apiContext = apiContext;
		this.notificationManager = notificationManager;
	}

	@Transactional
	@Scheduled(fixedRateString = "${notification.rateInterval}")
	public void sendNotifications() {
		List<CompletableFuture<Notification>> futures = new LinkedList<>();
		this.apiContext.getOperationsContext().getDatabaseRepository().getNotificationDao().asQueryable().where(((builder, root) ->
				builder.and(
						builder.or(
								builder.equal(root.get("notifyState"), NotifyState.PENDING), builder.equal(root.get("notifyState"), NotifyState.ERROR))
				, builder.equal(root.get("isActive"), ActiveStatus.ACTIVE)))).toListAsync().thenApplyAsync((notifications) -> {
			if (!notifications.isEmpty()) {
				notifications.forEach(notification -> {
					try {
						this.notificationManager.sendNotification(notification);
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
					}
				});
			}
			return notifications;
		}).thenApplyAsync((notifications) -> {
			notifications.forEach((notification) -> futures.add(this.apiContext.getOperationsContext().getDatabaseRepository().getNotificationDao().createOrUpdateAsync(notification)));
			return futures;
		}).join();

	}
}
