package de.walamana.models

import de.walamana.plugins.DateAsLong
import de.walamana.plugins.dbQuery
import kotlinx.serialization.Serializable
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import java.util.Date

@Serializable
data class GottesdienstGroup (
    val id: Int,
    val from: DateAsLong,
    val to: DateAsLong
)


object GottesdienstGroups : Table() {
    val id = integer("id").autoIncrement()
    val from = long("date_from")
    val to = long("date_to")

    override val primaryKey = PrimaryKey(id)
}

object GottesdienstGroupDao {

    fun ResultRow.toPlan() = GottesdienstGroup(
        this[GottesdienstGroups.id],
        Date(this[GottesdienstGroups.from]),
        Date(this[GottesdienstGroups.to])
    )

    suspend fun getPlans(amount: Int = 10, offset: Long = 0) = dbQuery {
        GottesdienstGroups.selectAll()
            .orderBy(GottesdienstGroups.from to SortOrder.DESC)
            .limit(amount, offset)
            .map { it.toPlan() }
    }

    suspend fun createPlan(from: Date, to: Date) = dbQuery {
        GottesdienstGroups.insert {
            it[GottesdienstGroups.from] = from.time
            it[GottesdienstGroups.to] = to.time
        }.resultedValues?.firstOrNull()?.toPlan()
    }

    suspend fun updatePlan(group: GottesdienstGroup): Boolean = dbQuery {
        GottesdienstGroups.upsert {
            it[id]= group.id
            it[from] = group.from.time
            it[to] = group.to.time
        }.resultedValues?.isNotEmpty() ?: false
    }

    suspend fun deletePlan(id: Int) = dbQuery {
        GottesdienstGroups.deleteWhere { GottesdienstGroups.id eq id } > 0
    }
}
