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
abstract class MessageDao {

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

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

    @Query("select * from Message where opposite_pin = :pin order by server_date desc")
    abstract fun getOpposite(pin: String): LiveData<List<Message>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    abstract suspend fun _insert(entity: Message)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    abstract suspend fun _insertSummary(entity: MessageSummary)

    @Query("delete from Message")
    abstract suspend fun deleteAll()

    suspend fun insert(entity: Message) {
        _insert(entity)
        _insertSummary(
            MessageSummary(
                l_pin = entity.opposite_pin,
                message_id = entity.message_id,
                last_update = System.currentTimeMillis()
            )
        )
    }

}