package eu.dnetlib.is.wfs;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
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.data.is.wf.model.WfProcessExecution;
import eu.dnetlib.data.is.wf.repository.WfProcessExecutionRepository;

@RestController
@RequestMapping("/ajax/wfs")
public class WfHistoryAjaxController {

	@Autowired
	private WfProcessExecutionRepository wfProcessExecutionRepository;

	@Deprecated
	public static final int MAX_NUMBER_OF_RECENT_WFS = 100;

	@GetMapping("/")
	public List<WfProcessExecution> history(
		@RequestParam(required = true) final int total,
		@RequestParam(required = false) final Long from,
		@RequestParam(required = false) final Long to) {
		if (from == null && to == null) {
			return wfProcessExecutionRepository.findAll(PageRequest.of(0, total, Sort.by("endDate").descending())).toList();
		} else if (from == null) {
			return wfProcessExecutionRepository.findByEndDateBetweenOrderByEndDateDesc(new Date(0), new Date(to));
		} else if (to == null) {
			return wfProcessExecutionRepository.findByEndDateBetweenOrderByEndDateDesc(new Date(from), new Date());
		} else {
			return wfProcessExecutionRepository.findByEndDateBetweenOrderByEndDateDesc(new Date(from), new Date(to));
		}
	}

	@GetMapping("/{processId}")
	public WfProcessExecution getProcess(@PathVariable final String processId) {
		return wfProcessExecutionRepository.findById(processId).get();
	}

}
