package eu.dnetlib.dsm;

import java.util.List;

import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import eu.dnetlib.dsm.domain.SimpleDatasourceInfo;
import eu.dnetlib.dsm.domain.SimpleResponse;
import eu.dnetlib.dsm.utils.ResponseUtils;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@RequestMapping("/api/dsm/2.0")
@ConditionalOnProperty(value = "openaire.api.enable.dsm", havingValue = "true")
@Tag(name = "OpenAIRE DSM API (version 2.0)", description = "the OpenAIRE Datasource Manager API 2.0")
public class DsmApiControllerV2 extends AbstractDsmController {

	@Autowired
	private DsmService dsmService;

	@GetMapping("/recentregistered/{size}")
	public SimpleResponse<SimpleDatasourceInfo> recentRegisteredV2(@PathVariable final int size) throws Throwable {
		final StopWatch stop = StopWatch.createStarted();
		final SimpleResponse<SimpleDatasourceInfo> rsp = dsmService.searchRecentRegisteredV2(size);
		return prepareResponse(1, size, stop, rsp);
	}

	@GetMapping("/countfirstcollect")
	public Long countFirstCollectAfter(@RequestParam final String fromDate,
		@RequestParam(required = false) final String typologyFilter) throws Throwable {
		return dsmService.countFirstCollect(fromDate, typologyFilter);
	}

	@GetMapping("/firstCollected")
	public SimpleResponse<SimpleDatasourceInfo> firstCollectedAfter(@RequestParam final String fromDate,
		@RequestParam(required = false) final String typologyFilter) throws Throwable {
		final StopWatch stop = StopWatch.createStarted();
		final List<SimpleDatasourceInfo> list = dsmService.getFirstCollectedAfter(fromDate, typologyFilter);
		final SimpleResponse<SimpleDatasourceInfo> rsp = ResponseUtils.simpleResponse(list);

		return prepareResponse(1, list.size(), stop, rsp);
	}

}
