package com.jaytux.simd.server

import kotlinx.serialization.Serializable
import org.jetbrains.exposed.sql.Expression
import org.jetbrains.exposed.sql.SizedIterable
import org.jetbrains.exposed.sql.SortOrder

@Serializable data class Paginated<T>(val page: Long, val totalPages: Long, val items: List<T>)

inline fun <reified T, reified R> SizedIterable<T>.paginated(page: Long, perPage: Int, crossinline mapper: (T) -> R): Paginated<R> {
    val total = this.count()
    val subset = this.offset(page * perPage).limit(perPage).map { item -> mapper(item) }
    return Paginated(page, total / perPage + if (total % perPage > 0) 1 else 0, subset)
}

fun <T> SizedIterable<T>.orderAsc(expr: Expression<*>) = this.orderBy(expr to SortOrder.ASC)

fun <T> SizedIterable<T>.emptyToNull() = if(empty()) null else this