package com.ustadmobile.core.db.dao

import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.ustadmobile.lib.db.composites.MessageAndOtherPerson
import com.ustadmobile.lib.db.entities.Message
import kotlin.Any
import kotlin.Int
import kotlin.Long
import kotlin.String

@Dao
public actual abstract class MessageDao {
  @Query(`value` =
      "\n        SELECT Message.*\n          FROM Message\n         WHERE (Message.messageSenderPersonUid = :accountPersonUid\n                AND Message.messageToPersonUid = :otherPersonUid)\n            OR (Message.messageSenderPersonUid = :otherPersonUid\n                AND Message.messageToPersonUid = :accountPersonUid) \n      ORDER BY Message.messageTimestamp DESC          \n    ")
  public actual abstract fun messagesFromOtherUserAsPagingSource(accountPersonUid: Long,
      otherPersonUid: Long): PagingSource<Int, Message>

  @Query(`value` =
      "\n        SELECT Person.*, LatestMessage.*, PersonPicture.*\n          FROM Person\n               JOIN Message LatestMessage\n                    ON LatestMessage.messageUid = \n                       (SELECT Message.messageUid\n                          FROM Message\n                         WHERE (Message.messageSenderPersonUid = :accountPersonUid\n                                AND Message.messageToPersonUid = Person.personUid)\n                            OR (Message.messageSenderPersonUid = Person.personUid\n                                AND Message.messageToPersonUid = :accountPersonUid)\n                       ORDER BY Message.messageTimestamp DESC\n                          LIMIT 1)\n                          \n                LEFT JOIN PersonPicture\n                          ON PersonPicture.personPictureUid = Person.personUid\n         WHERE :searchQuery = '%' \n               OR (Person.firstNames || ' ' || Person.lastName) LIKE :searchQuery\n      ORDER BY LatestMessage.messageTimestamp DESC\n    ")
  public actual abstract fun conversationsForUserAsPagingSource(searchQuery: String,
      accountPersonUid: Long): PagingSource<Int, MessageAndOtherPerson>

  @Insert(
    entity = Any::class,
    onConflict = 3,
  )
  public actual abstract suspend fun insert(message: Message)
}
