package eu.dnetlib.scholix.api.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import eu.dnetlib.dhp.schema.sx.api.model.v2.LinkProviderType;
import eu.dnetlib.scholix.api.ScholixException;
import eu.dnetlib.scholix.api.index.ScholixIndexManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@RequestMapping("/v2/LinkPublisher")
@Tag(name = "LinkPublisher : Operation related to the Link Publisher")
public class LinkPublisherV2 {

	@Autowired
	ScholixIndexManager manager;

	@Operation(summary = "Get All Publishers that provide source object", description = "Return a List of all Publishers that provide source objects in Scholix "
		+
		"links and the total number of links where the source object comes from this publisher")
	@GetMapping("/inSource")
	public List<LinkProviderType> getInSource(
		@Parameter(in = ParameterIn.QUERY, description = "Filter the link publisher name") @RequestParam(required = false) final String name)
		throws ScholixException {
		final List<Pair<String, Long>> result = manager.totalLinksPublisher(ScholixIndexManager.RelationPrefix.source, name);

		if (result == null) { return new ArrayList<>(); }

		return result.stream().map(s -> new LinkProviderType().name(s.getLeft()).totalRelationships(s.getValue().intValue())).collect(Collectors.toList());
	}

	@Operation(summary = "Get All Publishers that provide target object", description = "Return a List of all Publishers that provide source objects in Scholix "
		+
		"links and the total number of links where the target object comes from this publisher")
	@GetMapping("/inTarget")
	public List<LinkProviderType> getInTarget(
		@Parameter(in = ParameterIn.QUERY, description = "Filter the link publisher name") @RequestParam(required = false) final String name)
		throws ScholixException {
		final List<Pair<String, Long>> result = manager.totalLinksPublisher(ScholixIndexManager.RelationPrefix.target, name);

		if (result == null) { return new ArrayList<>(); }

		return result.stream().map(s -> new LinkProviderType().name(s.getLeft()).totalRelationships(s.getValue().intValue())).collect(Collectors.toList());
	}
}
