import backendRequest from 'lib/backend';
import { pagingHeader, readPagingHeader, sortingHeader, readSortingHeader } from 'lib/list-utils';


export function fetchFilterOptions(url) {
	return ({filter, ...opts}) => {
		let headers = {};
		return backendRequest(typeof url === "function" ? url({ filter, ...opts }) : url, 'GET', { params: filter })
	}
}


export function listRequest(url) {
	return ({ filter, paging, sorting, ...opts }) => {
		let headers = {};
		
		let ph = pagingHeader(paging);
		if (ph) {
			Object.assign(headers, ph);
		}
		let sh = sortingHeader(sorting);
		if (sh) {
			Object.assign(headers, sh);
		}
		return backendRequest(typeof url === "function" ? url({ filter, ...opts }) : url, 'GET', { params: filter, headers })
	}
}


export function listResponse() {
	return ({ headers, body } = {}, { paging, sorting } = {}) => {
		return {
			data: body || [],
			paging: readPagingHeader(headers, paging),
			sorting: readSortingHeader(headers, sorting)
		}
	}
}

