import { Iterable, List } from "immutable";


const DEFAULT_PAGE_SIZE = 10;


export function pagingHeader(paging) {
	if (!paging) {
		return;
	}

	return {
		'X-Paging': true,
		'X-Paging-Page': paging.page || 0,
		'X-Paging-PageSize': paging.pageSize || DEFAULT_PAGE_SIZE
	};
}


export function sortingHeader(sorting) {
	if (!(sorting && sorting.field && sorting.trend)) {
		return;
	}

	return {
		'X-Sorting': true,
		'X-Sorting-Field': sorting.field,
		'X-Sorting-Trend': sorting.trend
	};
}


export const readPagingHeader = function(headers = {}, paging) {
	if (!headers["x-paging"]) {
		return paging;
	}

	const ps = headers["x-paging-page"] * 1;
	const psize = headers["x-paging-pagesize"] * 1;
	const pcs = headers["x-paging-pagescount"] * 1;

	return {
		...paging,
		page: isNaN(ps) ? 0 : ps,
		pageSize: isNaN(psize) ? ( paging && paging.pageSize || DEFAULT_PAGE_SIZE ) : psize,
		pagesCount: isNaN(pcs) ? 1 : pcs
	};
}


export const readSortingHeader = function(headers = {}, sorting) {
	if (!headers["x-sorting"]) {
		return {};
	}

	const field = headers["x-sorting-field"];
	const trend = headers["x-sorting-trend"];

	return { ...sorting, field, trend }
}


export function memoryPaging(list, pageSize = DEFAULT_PAGE_SIZE) {
	let page = 0;
	let pagesCount = 0;

	if (List.isList(list)) {
		pagesCount = list.size / (pageSize || DEFAULT_PAGE_SIZE);

	} else if (Array.isArray(list)) {
		pagesCount = list.length / (pageSize || DEFAULT_PAGE_SIZE);
	}



	return {
		page,
		pageSize,
		pagesCount
	}
	
}


