package eu.dnetlib.broker.controllers;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import eu.dnetlib.broker.LiteratureBrokerServiceApplication;
import eu.dnetlib.broker.common.subscriptions.Subscription;
import eu.dnetlib.broker.common.subscriptions.SubscriptionRepository;
import eu.dnetlib.broker.matchers.SubscriptionEventMatcher;
import eu.dnetlib.common.controller.AbstractDnetController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@Profile("!openaire")
@RestController
@RequestMapping("/api/matching")
@Tag(name = LiteratureBrokerServiceApplication.TAG_MATCHING)
public class StartMatchingController extends AbstractDnetController {

	@Autowired
	private SubscriptionRepository subscriptionRepo;

	@Autowired(required = false)
	private SubscriptionEventMatcher subscriptionEventMatcher;

	@Operation(summary = "Launch the thread that produces new notifications")
	@GetMapping("/start")
	public List<String> startMatching() {
		if (subscriptionEventMatcher != null) {
			this.subscriptionRepo.findAll().forEach(this.subscriptionEventMatcher::startMatching);
			return Arrays.asList("done");
		} else {
			return Arrays.asList("matching is disabled");
		}
	}

	@Operation(summary = "Launch the thread that produces new notifications by subscriptuion id")
	@GetMapping("/start/{subscriptionId}")
	public List<String> startMatching(@PathVariable final String subscriptionId) {
		final Optional<Subscription> s = subscriptionRepo.findById(subscriptionId);

		if (subscriptionEventMatcher == null) {
			return Arrays.asList("matching is disabled");
		} else if (s.isPresent()) {
			subscriptionEventMatcher.startMatching(s.get());
			return Arrays.asList("done");
		} else {
			return Arrays.asList("subscription not present");
		}
	}

}
