/*
 * Queue - A Queueing system that can be used to handle labs in higher education
 * Copyright (C) 2016-2021  Delft University of Technology
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package nl.tudelft.queue;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

/**
 * A utility class used for turning lists into pages.
 */
public class PageUtil {
	/**
	 * Turns the given list of values into a page of values which represent a sublist of the original.
	 *
	 * @param  pageable The pageable describing what to show on the page.
	 * @param  values   The total list of values of which a page needs to be shown.
	 * @param  <T>      The type of the values in the page.
	 * @return          The Page cut out from the original list of values.
	 */
	public static <T> Page<T> toPage(Pageable pageable, List<T> values) {
		int start = (int) pageable.getOffset();
		int end = Math.min(start + pageable.getPageSize(), values.size());

		if (start < 0 || start >= values.size()) {
			return new PageImpl<>(List.of(), pageable, values.size());
		}

		return new PageImpl<>(values.subList(start, end), pageable, values.size());
	}
}
