package gaf3.core.data

import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort

class PageParam {
    var skip: Int = 0
    var limit: Int = 100
    var exact: Boolean = true
    var sort: SortParam? = null

    /**
     * 添加默认排序
     */
    fun sortBy(direction: Sort.Direction, vararg properties: String): PageParam {
        if(this.sort == null) this.sort = SortParam.by(direction, *properties)
        return this
    }

    /**
     * 添加默认排序
     */
    fun sortBy(vararg properties: String): PageParam {
        if(this.sort == null) this.sort = SortParam.by(*properties)
        return this
    }

    fun toPageRequest(): PageRequest {
        val page:Int = skip/limit
        return if (sort != null && sort!!.property.isNotEmpty()) {
            PageRequest.of(page, limit, sort!!.toSort())
        } else {
            PageRequest.of(page, limit)
        }
    }



    companion object {
        fun of(skip: Int = 0, limit: Int = 100, exact: Boolean = true): PageParam {
            return PageParam().apply {
                this.skip = skip
                this.limit = limit
                this.exact = exact
            }
        }
    }
}

class SortParam {
    var direction: String = "ASC"
    var property: Array<String> = arrayOf()

    fun toSort(): Sort {
        return Sort.by(Sort.Direction.fromString(direction), *property)
    }

    companion object {
        fun by(direction: Sort.Direction, vararg properties: String): SortParam {
            return SortParam().apply {
                this.direction = direction.name
                this.property = arrayOf(*properties)
            }
        }
        fun by(vararg properties: String): SortParam {
            return by(Sort.Direction.ASC, *properties)
        }
    }
}
