package eu.dnetlib.openaire.project;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

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

	private static final String BASE_PATH = "/export/";
	private static final String NO_FILTER = "ALL";

	public ProjectQueryParams generateParams(final HttpServletRequest request,
			final String startFrom,
			final String startUntil,
			final String endFrom,
			final String endUntil) {
		ProjectQueryParams params = new ProjectQueryParams();

		String[] arr = request.getServletPath().replace(BASE_PATH, "").split("\\/");
		if (arr.length != 5) throw new IllegalArgumentException("Invalid url");

		params.setFundingProgramme(arr[0]);
		String stream = NO_FILTER.equals(arr[1]) ? null : arr[1];
		String substream = NO_FILTER.equals(arr[2]) ? null : arr[2];
		if (substream == null) {
			params.setFundingPath(stream);
		} else {
			if (stream == null) {
				stream = "%";
			}
			params.setFundingPath(stream + "::" + substream);
		}
		// params.setSpecificProgramme(NO_FILTER.equals(arr[1]) ? null : arr[1]);
		// params.setSubdivision(NO_FILTER.equals(arr[2]) ? null : arr[2]);
		// NB: arr[3] should be 'projects'
		// NB: arr[4] should be '[file].do'
		params.setStartFrom(startFrom);
		params.setStartUntil(startUntil);
		params.setEndFrom(endFrom);
		params.setEndUntil(endUntil);

		return params;
	}
}
