package de.sebse.fuplanner2.database

import androidx.lifecycle.LiveData
import androidx.paging.DataSource
import androidx.room.*

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

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

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

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

    @Query("SELECT * FROM announcement WHERE uid = :announcementId LIMIT 1")
    fun getAnnouncementById2(announcementId: Long): LiveData<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>)
}
