package com.ustadmobile.core.db.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.ustadmobile.lib.db.entities.PersonPicture
import kotlin.Any
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlinx.coroutines.flow.Flow

@Dao
public actual abstract class PersonPictureDao : BaseDao<PersonPicture>, ImageDao {
  @Insert(
    onConflict = 1,
    entity = Any::class,
  )
  public actual abstract suspend fun upsert(personPicture: PersonPicture)

  @Query(`value` =
      "\n        SELECT * \n          FROM PersonPicture \n         WHERE personPictureUid = :personUid\n           AND CAST(personPictureActive AS INTEGER) = 1\n         ")
  public actual abstract suspend fun findByPersonUidAsync(personUid: Long): PersonPicture?

  @Query(`value` =
      "\n         SELECT * \n           FROM PersonPicture \n          WHERE personPictureUid = :personUid \n          ")
  public actual abstract fun findByPersonUidLive(personUid: Long): Flow<PersonPicture?>

  @Query(`value` =
      "\n        SELECT * \n          FROM PersonPicture \n         WHERE personPictureUid = :personUid\n          AND CAST(personPictureActive AS INTEGER) = 1\n        LIMIT 1\n        ")
  public actual abstract fun findByPersonUidAsFlow(personUid: Long): Flow<PersonPicture?>

  @Update(
    entity = Any::class,
    onConflict = 3,
  )
  public actual abstract suspend fun updateAsync(personPicture: PersonPicture)

  @Query(`value` =
      "\n        UPDATE PersonPicture\n           SET personPictureLct = :time\n         WHERE personPictureUid = :uid   \n    ")
  public actual abstract suspend fun updateLct(uid: Long, time: Long)

  @Query(`value` =
      "\n        UPDATE PersonPicture\n           SET personPictureUri = :uri,\n               personPictureThumbnailUri = :thumbnailUri,\n               personPictureLct = :time\n         WHERE personPictureUid = :uid      \n    ")
  actual abstract override suspend fun updateUri(
    uid: Long,
    uri: String?,
    thumbnailUri: String?,
    time: Long,
  )

  @Query(`value` =
      "\n        UPDATE TransferJobItem\n           SET tjiEntityEtag = \n               (SELECT personPictureLct\n                  FROM PersonPicture\n                 WHERE personPictureUid = :entityUid)\n         WHERE tjiUid = :transferJobItemUid      \n    ")
  public actual abstract suspend fun updateTransferJobItemEtag(entityUid: Long,
      transferJobItemUid: Int)
}
