package io.nexilis.service.data.daos

import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import io.nexilis.service.data.entities.*

@Dao
interface MessageStatusDao {

    @Query("select * from MessageStatus")
    fun getAll(): LiveData<List<MessageStatus>>

    @Query("select * from MessageStatus where message_id = :id")
    fun get(id: String): LiveData<List<MessageStatus>>

    @Query("select * from MessageStatus where message_id = :id and f_pin = :pin")
    fun get(id: String, pin: String): LiveData<MessageStatus>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(entity: MessageStatus)

    @Query("update MessageStatus set status = :status, last_update = :lastUpdate where message_id = :messageId and f_pin = :pin")
    suspend fun updateStatus(
        status: Int,
        lastUpdate: Long = System.currentTimeMillis(),
        messageId: String,
        pin: String
    )

    @Query("update MessageStatus set status = :status, last_update = :lastUpdate, time_delivered = :timeDelivered where message_id = :messageId and f_pin = :pin and status < :status")
    suspend fun updateDelivered(
        status: Int,
        lastUpdate: Long = System.currentTimeMillis(),
        timeDelivered: Long,
        messageId: String,
        pin: String
    )

    @Query("update MessageStatus set status = :status, last_update = :lastUpdate, time_read = :timeRead where message_id = :messageId and f_pin = :pin and status < :status")
    suspend fun updateRead(
        status: Int,
        lastUpdate: Long = System.currentTimeMillis(),
        timeRead: Long,
        messageId: String,
        pin: String
    )

    @Query("update MessageStatus set status = :status, last_update = :lastUpdate, time_ack = :timeAck where message_id = :messageId and f_pin = :pin and status < :status")
    suspend fun updateAck(
        status: Int,
        lastUpdate: Long = System.currentTimeMillis(),
        timeAck: Long,
        messageId: String,
        pin: String
    )

    @Query("delete from MessageStatus")
    suspend fun deleteAll()

}