package com.ustadmobile.core.db.dao

import androidx.room.Dao
import androidx.room.Query
import com.ustadmobile.lib.db.entities.XObjectEntity
import kotlin.Long
import kotlin.String
import kotlin.Unit

@Dao
public actual abstract class XObjectDao : BaseDao<XObjectEntity> {
  @Query(`value` =
      "\n     REPLACE INTO XObjectEntityReplicate(xoePk, xoeDestination)\n      SELECT DISTINCT XObjectEntity.xObjectUid AS xoePk,\n             :newNodeId AS xoeDestination\n        FROM XObjectEntity\n       WHERE XObjectEntity.xObjectLct != COALESCE(\n             (SELECT xoeVersionId\n                FROM XObjectEntityReplicate\n               WHERE xoePk = XObjectEntity.xObjectUid\n                 AND xoeDestination = :newNodeId), 0) \n      /*psql ON CONFLICT(xoePk, xoeDestination) DO UPDATE\n             SET xoePending = true\n      */       \n    ")
  public actual abstract suspend fun replicateOnNewNode(newNodeId: Long): Unit

  @Query(`value` =
      "\n REPLACE INTO XObjectEntityReplicate(xoePk, xoeDestination)\n  SELECT DISTINCT XObjectEntity.xObjectUid AS xoeUid,\n         UserSession.usClientNodeId AS xoeDestination\n    FROM ChangeLog\n         JOIN XObjectEntity\n             ON ChangeLog.chTableId = 64\n                AND ChangeLog.chEntityPk = XObjectEntity.xObjectUid\n         JOIN UserSession ON UserSession.usStatus = 1\n   WHERE UserSession.usClientNodeId != (\n         SELECT nodeClientId \n           FROM SyncNode\n          LIMIT 1)\n     AND XObjectEntity.xObjectLct != COALESCE(\n         (SELECT xoeVersionId\n            FROM XObjectEntityReplicate\n           WHERE xoePk = XObjectEntity.xObjectUid\n             AND xoeDestination = UserSession.usClientNodeId), 0)\n /*psql ON CONFLICT(xoePk, xoeDestination) DO UPDATE\n     SET xoePending = true\n  */               \n    ")
  public actual abstract suspend fun replicateOnChange(): Unit

  @Query(`value` = "SELECT * from XObjectEntity WHERE objectId = :id")
  public actual abstract fun findByObjectId(id: String?): XObjectEntity?

  @Query(`value` = "SELECT * from XObjectEntity WHERE xObjectUid = :xObjectUid")
  public actual abstract fun findByXobjectUid(xObjectUid: Long): XObjectEntity?
}
