package eu.dnetlib.broker.controllers;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;

import eu.dnetlib.broker.LiteratureBrokerServiceApplication;
import eu.dnetlib.broker.common.elasticsearch.Event;
import eu.dnetlib.broker.common.elasticsearch.EventRepository;
import eu.dnetlib.broker.common.elasticsearch.EventStatsManager;
import eu.dnetlib.broker.common.elasticsearch.EventStatsManager.BrowseEntry;
import eu.dnetlib.broker.common.subscriptions.Subscription;
import eu.dnetlib.broker.common.subscriptions.SubscriptionRepository;
import eu.dnetlib.common.controller.AbstractDnetController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@RequestMapping("/api/events")
@Tag(name = LiteratureBrokerServiceApplication.TAG_EVENTS)
public class EventsController extends AbstractDnetController {

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

	@Autowired
	private EventRepository eventRepository;

	@Autowired
	private SubscriptionRepository subscriptionRepo;

	@Autowired
	private EventStatsManager eventStatsManager;

	@Operation(summary = "Return an event by ID")
	@GetMapping("/{id}")
	public Event getEvent(@PathVariable final String id) {
		return eventRepository.findById(id).get();
	}

	@Operation(summary = "Delete an event by ID")
	@DeleteMapping("/{id}")
	public void deleteEvent(@PathVariable final String id) {
		eventRepository.deleteById(id);
	}

	@Operation(summary = "Save an event by ID")
	@PostMapping("/{id}")
	public Event saveEvent(@RequestBody final Event event) {
		return eventRepository.save(event);
	}

	@Operation(summary = "Return a page of events")
	@GetMapping("/list/{page}/{pageSize}")
	public List<Event> events(
		@PathVariable final int page,
		@PathVariable final int pageSize) {
		return Lists.newArrayList(eventRepository.findAll(PageRequest.of(page, pageSize)));
	}

	@Operation(summary = "Return a page of events by topic")
	@GetMapping("/byTopic/{page}/{pageSize}")
	public List<Event> eventsByTopic(
		@PathVariable final int page,
		@PathVariable final int pageSize,
		@RequestParam final String topic) {
		return Lists.newArrayList(eventRepository.findByTopic(topic, PageRequest.of(page, pageSize)));
	}

	@Operation(summary = "Delete all the events")
	@DeleteMapping("/all")
	public Map<String, Object> clearEvents() {
		eventRepository.deleteAll();
		final Map<String, Object> res = new HashMap<>();
		res.put("deleted", true);
		return res;
	}

	@Operation(summary = "Delete the expired events")
	@DeleteMapping("/expired")
	public Map<String, Object> deleteExpiredEvents() {
		return deleteEventsByExpiryDate(0, new Date().getTime());
	}

	@Operation(summary = "Delete the events with the creationDate in a range")
	@DeleteMapping("/byCreationDate/{from}/{to}")
	public Map<String, Long> deleteEventsByCreationDate(@PathVariable final long from, @PathVariable final long to) {
		final Map<String, Long> res = new HashMap<>();
		res.put("deleted", eventRepository.deleteByCreationDateBetween(from, to));
		res.put("from", from);
		res.put("to", to);

		log.info(String.format("Deleted %s events in creationDate range %s-%s", res.get("deleted"), from, to));

		return res;
	}

	@Operation(summary = "Delete the events with the expiryDate in a range")
	@DeleteMapping("/byExpiryDate/{from}/{to}")
	public Map<String, Object> deleteEventsByExpiryDate(@PathVariable final long from, @PathVariable final long to) {
		new Thread(() -> {
			final long n = eventRepository.deleteByExpiryDateBetween(from, to);
			log.info(String.format("Deleted %s events in expiryDate 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;
	}

	@Operation(summary = "Return the topics of the indexed events (all)")
	@GetMapping("/topics/all")
	public List<BrowseEntry> browseTopics() {
		return eventStatsManager.browseTopics();
	}

	@Operation(summary = "Return the topics of the indexed events (only with subscriptions)")
	@GetMapping("/topics/withSubscriptions")
	public List<BrowseEntry> browseTopicsWithSubscriptions() {

		final Iterable<Subscription> iter = subscriptionRepo.findAll();

		final Set<String> validTopics = StreamSupport.stream(iter.spliterator(), false)
			.map(Subscription::getTopic)
			.collect(Collectors.toSet());

		return this.browseTopics()
			.stream()
			.filter(e -> validTopics.contains(e.getValue()))
			.collect(Collectors.toList());
	}

}
