package grmi

import (
	"strconv"
)

const (
	PageSize    = "pageSize"
	_PageSize   = "_pageSize"
	PageNumber  = "pageNumber"
	_PageNumber = "_pageNumber"
)

type Paging struct {
	Number int64
	Size   int64
}

func NewPaging() *Paging {
	return &Paging{Number: 1, Size: 10}
}

func (self *Paging) Offset() int64 {
	return (self.Number - 1) * self.Size
}

func (self *Paging) Fill(urlParameters map[string]string) bool {
	size, hasSzie := getPageSize(urlParameters)
	number, hasNumber := getPageIndex(urlParameters)
	if hasSzie || hasNumber {
		self.Size = size
		self.Number = number
		return true
	}
	return false
}

func getValue(urlParameters map[string]string, names []string, defaultValue int64) (int64, bool) {
	for _, name := range names {
		if urlParameter, ok := urlParameters[name]; ok {
			value, err := strconv.ParseInt(urlParameter, 10, 64)
			if err == nil {
				return value, true
			}
		}
	}
	return defaultValue, false
}

func getPageIndex(urlParameters map[string]string) (int64, bool) {
	return getValue(urlParameters, []string{_PageNumber, PageNumber}, 1)
}

func getPageSize(urlParameters map[string]string) (int64, bool) {
	return getValue(urlParameters, []string{_PageSize, PageSize}, 1)
}
