package de.sebse.fuplanner2.database

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

@Dao
interface AnnouncementDao {
    @Query("SELECT * FROM announcement WHERE courseId = :courseId ORDER BY createdOn ASC")
    fun getAll1(courseId: Long): DataSource.Factory<Int, Announcement>

    @Query("SELECT * FROM announcement WHERE courseId = :courseId ORDER BY createdOn ASC")
    fun getAll2(courseId: Long): List<Announcement>

    @Query("SELECT * FROM announcement WHERE uid = :announcementId LIMIT 1")
    fun getAnnouncementById(announcementId: Long): Announcement

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(announcement: Announcement): Long

    @Update(onConflict = OnConflictStrategy.REPLACE)
    fun update(announcement: Announcement)

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

    @Transaction
    fun upsert(announcements: List<Announcement>) {
        announcements.forEach { announcement ->
            upsert(announcement)
        }
    }

    @Delete
    fun delete(announcement: Announcement)

    @Delete
    fun delete(announcements: List<Announcement>)
}