package com.ustadmobile.core.db.dao

import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Update
import com.ustadmobile.lib.db.entities.ContentEntryPicture
import kotlin.Long
import kotlin.Unit

@Dao
public actual abstract class ContentEntryPictureDao : BaseDao<ContentEntryPicture> {
  @Query(`value` =
      "\n     REPLACE INTO ContentEntryPictureReplicate(cepPk, cepDestination)\n         SELECT DISTINCT cepUid AS cepPK,\n                :newNodeId AS siteDestination\n           FROM ContentEntryPicture\n          WHERE ContentEntryPicture.cepTimestamp != COALESCE(\n                (SELECT cepVersionId\n                   FROM ContentEntryPictureReplicate\n                  WHERE cepPk = ContentEntryPicture.cepUid\n                    AND cepDestination = :newNodeId), -1) \n         /*psql ON CONFLICT(cepPk, cepDestination) DO UPDATE\n                SET cepPending = true\n         */       \n    ")
  public actual abstract suspend fun replicateOnNewNode(newNodeId: Long): Unit

  @Query(`value` =
      "\n  REPLACE INTO ContentEntryPictureReplicate(cepPk, cepDestination)\n         SELECT DISTINCT ContentEntryPicture.cepUid AS cepPk,\n                UserSession.usClientNodeId AS siteDestination\n           FROM ChangeLog\n                JOIN ContentEntryPicture\n                    ON ChangeLog.chTableId = 138\n                       AND ChangeLog.chEntityPk = ContentEntryPicture.cepUid\n                JOIN UserSession ON UserSession.usStatus = 1\n          WHERE UserSession.usClientNodeId != (\n                SELECT nodeClientId \n                  FROM SyncNode\n                 LIMIT 1)\n            AND ContentEntryPicture.cepTimestamp != COALESCE(\n                (SELECT cepVersionId\n                   FROM ContentEntryPictureReplicate\n                  WHERE cepPk = ContentEntryPicture.cepUid\n                    AND cepDestination = UserSession.usClientNodeId), 0)     \n        /*psql ON CONFLICT(cepPk, cepDestination) DO UPDATE\n            SET cepPending = true\n         */               \n    ")
  public actual abstract suspend fun replicateOnChange(): Unit

  @Query(`value` =
      "\n        SELECT * \n          FROM ContentEntryPicture \n         WHERE cepContentEntryUid = :entryUid\n           AND cepActive\n      ORDER BY cepTimestamp DESC \n         LIMIT 1\n         ")
  public actual abstract suspend fun findByContentEntryUidAsync(entryUid: Long):
      ContentEntryPicture?

  @Query(`value` =
      "\n         SELECT * \n          FROM ContentEntryPicture \n         WHERE cepContentEntryUid = :entryUid\n           AND cepActive\n      ORDER BY cepTimestamp DESC \n         LIMIT 1\n         ")
  public actual abstract fun findByContentEntryUidLive(entryUid: Long):
      LiveData<ContentEntryPicture?>

  @Update(onConflict = 3)
  public actual abstract suspend fun updateAsync(ContentEntryPicture: ContentEntryPicture): Unit
}
