package eu.dnetlib.broker.controllers;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import eu.dnetlib.broker.common.elasticsearch.Notification;
import eu.dnetlib.broker.common.elasticsearch.NotificationRepository;
import eu.dnetlib.common.controller.AbstractDnetController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@RequestMapping("/api/notifications")
@Tag(name = "LiteratureBrokerServiceApplication.TAG_NOTIFICATIONS")
public class NotificationsController extends AbstractDnetController {

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

	@Autowired
	private NotificationRepository notificationRepository;

	@Operation(summary = "Return a notification by ID")
	@GetMapping("/{id}")
	public Notification getNotification(@PathVariable final String id) {
		return notificationRepository.findById(id).get();
	}

	@Operation(summary = "Delete a notification by ID")
	@DeleteMapping("/{id}")
	public void deleteNotification(@PathVariable final String id) {
		notificationRepository.deleteById(id);
	}

	@Operation(summary = "Save a notification by ID")
	@PostMapping("/{id}")
	public Notification saveNotification(@RequestBody final Notification notification) {
		return notificationRepository.save(notification);
	}

	@Operation(summary = "Delete all notifications")
	@DeleteMapping("")
	public void deleteAllNotifications() {
		notificationRepository.deleteAll();
	}

	@Operation(summary = "Delete the notifications with the date in a range")
	@DeleteMapping("/byDate/{from}/{to}")
	public Map<String, Object> deleteNotificationsByDate(@PathVariable final long from, @PathVariable final long to) {
		new Thread(() -> {
			final long n = notificationRepository.deleteByDateBetween(from, to);
			log.info(String.format("Deleted %s notifications in date range %s-%s", n, from, to));
		}).start();

		final Map<String, Object> res = new HashMap<>();
		res.put("status", "deleting...");
		res.put("from", from);
		res.put("to", to);
		return res;
	}

}
