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.RestController;

import eu.dnetlib.common.controller.AbstractDnetController;
import eu.dnetlib.dhp.schema.sx.api.model.v1.LinkPublisher;
import eu.dnetlib.scholix.api.ScholixException;
import eu.dnetlib.scholix.api.index.ScholixIndexManager;
import io.micrometer.core.annotation.Timed;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@RequestMapping("/v1")
@Tag(name = "Datasources")
public class DatasourceV1 extends AbstractDnetController {

	@Autowired
	private ScholixIndexManager manager;

	@Timed(value = "scholix.v1.datasources", description = "Time taken to return all datasources on Version 1.0 of Scholix")
	@Operation(summary = "Get all Datasources", description = "returns a list of all datasources")
	@GetMapping("/listDatasources")
	public List<LinkPublisher> getDatasources() throws ScholixException {

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

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

		return result.stream().map(p -> new LinkPublisher().name(p.getKey()).totalRelationships(p.getValue().intValue())).collect(Collectors.toList());

	}
}
