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")
@Tag(name = "LinkProvider : Operation related to the Link Provider")
public class LinkProviderV2 {

	@Autowired
	ScholixIndexManager manager;

	@Operation(summary = "Get all Link Providers", description = "Return a list of link provider and relative number of relations")
	@GetMapping("/LinkProvider")
	public List<LinkProviderType> getLinkProviders(
		@Parameter(in = ParameterIn.QUERY, description = "Filter the link provider name") @RequestParam(required = false) final String name)
		throws ScholixException {

		final List<Pair<String, Long>> result = manager.totalLinksByProvider(name);

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

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

	}
}
