package de.sebse.fuplanner2.database

import androidx.paging.DataSource
import androidx.room.*
import de.sebse.fuplanner2.utils.console

@Dao
interface EventDao {
    @Query("SELECT * FROM event WHERE startDateTime >= :start AND startDateTime <= :end")
    fun getAllBetween(start: Long, end: Long): List<Event>

    @Query("SELECT * FROM event WHERE courseId = :courseId ORDER BY startDateTime ASC")
    fun getAll1(courseId: Long): DataSource.Factory<Int, Event>

    @Query("SELECT * FROM event WHERE courseId = :courseId ORDER BY startDateTime ASC")
    fun getAll2(courseId: Long): List<Event>

    @Query("SELECT * FROM event WHERE uid = :eventId LIMIT 1")
    fun getEventById(eventId: Long): Event

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(event: Event): Long

    @Update(onConflict = OnConflictStrategy.REPLACE)
    fun update(event: Event)

    @Transaction
    fun upsert(event: Event) {
        val id = insert(event)
        if (id == -1L) {
            update(event)
        } else {
            event.uid = id
        }
    }

    @Transaction
    fun upsert(events: List<Event>) {
        events.forEach { event ->
            upsert(event)
        }
    }

    @Delete
    fun delete(event: Event)

    @Delete
    fun delete(events: List<Event>)
}