package de.sebse.fuplanner2.database

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


@Dao
interface NotificationDao {
    @Query("SELECT * FROM notification ORDER BY created DESC")
    fun getAllPaged(): DataSource.Factory<Int, Notification>

    @Query("SELECT * FROM notification WHERE channelId = :channelId AND read = 0")
    fun loadAllUnreadByChannelId(channelId: String): List<Notification>

    @Query("SELECT COUNT(uid) FROM notification WHERE read = 0")
    fun getUnreadRowCount(): LiveData<Int>

    @Query("UPDATE notification SET read = 1")
    fun setRead()

    @Query("UPDATE notification SET read = 1 WHERE uid = :notificationId")
    fun setRead(notificationId: Int)

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(notification: Notification): Long

    @Update(onConflict = OnConflictStrategy.REPLACE)
    fun update(notification: Notification)

    @Transaction
    fun upsert(notification: Notification) {
        val id = insert(notification)
        if (id == -1L) {
            update(notification)
        }
    }

    @Transaction
    fun upsert(notifications: List<Notification>) {
        notifications.forEach { notification ->
            upsert(notification)
        }
    }

    @Delete
    fun delete(notification: Notification)

    @Query("DELETE FROM notification WHERE created < (STRFTIME('%s', 'now') * 1000 - 31536000000) AND read")
    fun deleteOld()

}