package service

import (
	"reflect"
)

func Pagination(page uint32, itemsPerPage uint32, items interface{}) interface{} {
	t := reflect.TypeOf(items)
	if t.Kind() != reflect.Slice {
		return items
	}
	startIndex := GetStartIndex(int(page), GetSize(int(itemsPerPage)))
	v := reflect.ValueOf(items)
	if startIndex >= v.Len() {
		//invalid pagination parameter, return an empty result set
		return reflect.MakeSlice(t, 0, 0).Interface()
	}

	endIndex := startIndex + GetSize(int(itemsPerPage))
	if endIndex > v.Len() {
		endIndex = v.Len()
	}
	reflectSlice := reflect.MakeSlice(t, 0, endIndex-startIndex)
	for i := startIndex; i < endIndex; i++ {
		reflectSlice = reflect.Append(reflectSlice, v.Index(i))
	}
	return reflectSlice.Interface()
}

func GetStartIndex(page int, itemsPerPage int) int {
	if page <= 0 {
		page = 1
	}
	return (page - 1) * GetSize(itemsPerPage)
}

func GetSize(itemsPerPage int) int {
	if itemsPerPage <= 0 {
		itemsPerPage = 10
	}
	return itemsPerPage
}
