import { TFetchingRequest } from '../PaginatedResult';
import { OffsetPaginatedResult } from "../OffsetPaginatedResult";
import { OffsetPaging } from "../OffsetPaging";

const DATASOURCE_SIZE: number = 100;
let dataSource: string[] = [];

const populateDataSource = () => {
	dataSource = [];
	for (let index = 0; index < DATASOURCE_SIZE; index++) {
		dataSource.push(`Linea #${index}`);
	}
};

const fetchingDataMock = jest.fn((request: TFetchingRequest) => {
	const { paging } = request;
	return dataSource.slice(paging.start, paging.start + paging.limit);
});

describe.skip('OffsetPaginatedResult', () => {
	beforeEach(() => {
		populateDataSource();
	});

	afterEach(() => {
		jest.clearAllMocks();
	})

	test('se recupera la primera página', () => {
		let result: OffsetPaginatedResult<string[]> = OffsetPaginatedResult.create({
			fetchingFn: fetchingDataMock,
			fetchingParams: null,
			totalCount: (DATASOURCE_SIZE),
		});

		result = result.start(OffsetPaging.create(0, 25), null);
		result.getData();
		expect(fetchingDataMock.mock.calls.length).toBe(1);
	});

	test('se recuperan todos las páginas', () => {
		let offset = 0;
		let limit = 25;
		let offsetPaging = OffsetPaging.create(offset, limit);

		let result: OffsetPaginatedResult<string[]> = OffsetPaginatedResult.create({
			fetchingFn: fetchingDataMock,
			fetchingParams: null,
			totalCount: DATASOURCE_SIZE,
		});

		result = result.start(offsetPaging, null);
		do {
			result.getData();
		} while (result.next());

		expect(fetchingDataMock.mock.calls.length).toBe(DATASOURCE_SIZE / limit);
	});

	test('se recuperan los datos correctos en cada página', () => {
		let offset = 0;
		let limit = 25;
		let data: string[] = undefined;
		let offsetPaging = OffsetPaging.create(offset, limit);

		let result: OffsetPaginatedResult<string[]> = OffsetPaginatedResult.create({
			fetchingFn: fetchingDataMock,
			fetchingParams: null,
			totalCount: DATASOURCE_SIZE,
		});

		result = result.start(offsetPaging, null);
		do {
			data = result.getData();
			expect(data).toStrictEqual(dataSource.slice(offset, offset + limit));
			offset = offset + limit;
		} while (result.next());

		expect(fetchingDataMock.mock.calls.length).toBe(DATASOURCE_SIZE / limit);
	});
});
