package eu.dnetlib.openaire.funders;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;

import eu.dnetlib.openaire.exporter.exceptions.FundersApiException;
import eu.dnetlib.openaire.exporter.model.funders.ExtendedFunderDetails;
import eu.dnetlib.openaire.exporter.model.funders.FunderDetails;

@Component
@ConditionalOnProperty(value = "openaire.exporter.enable.funders", havingValue = "true")
public class FunderDao {

	@Autowired
	private FunderRepository funderRepository;

	public ExtendedFunderDetails getExtendedFunderDetails(final String funderId) throws FundersApiException {
		return ConversionUtils
			.asExtendedFunderDetails(funderRepository.findById(funderId).orElseThrow(() -> new FundersApiException("Funder not found. ID:  " + funderId)));
	}

	public List<FunderDetails> listFunderDetails(final int page, final int size) throws FundersApiException {
		return funderRepository.findAll(PageRequest.of(page, size))
			.getContent()
			.stream()
			.map(ConversionUtils::asFunderDetails)
			.collect(Collectors.toList());
	}

	public List<String> listFunderIds(final int page, final int size) throws FundersApiException {
		return funderRepository.findAll(PageRequest.of(page, size))
			.getContent()
			.stream()
			.map(f -> f.getId())
			.collect(Collectors.toList());
	}

}
