package com.ustadmobile.core.db.dao

import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.ustadmobile.lib.db.entities.ContentJob
import kotlin.Boolean
import kotlin.Long
import kotlin.String
import kotlin.Unit

@Dao
public actual abstract class ContentJobDao {
  @Insert(onConflict = 3)
  public actual abstract suspend fun insertAsync(contentJob: ContentJob): Long

  @Query(`value` =
      "\n        SELECT ContentJob.*\n          FROM ContentJob\n         WHERE cjUid = :cjUid \n    ")
  public actual abstract fun findByUid(cjUid: Long): ContentJob?

  @Query(`value` =
      "\n        SELECT ContentJob.*\n          FROM ContentJob\n         WHERE cjUid = :cjUid \n    ")
  public actual abstract suspend fun findByUidAsync(cjUid: Long): ContentJob?

  @Query(`value` =
      "\n        SELECT ContentJob.*\n          FROM ContentJob\n         WHERE cjUid = :cjUid\n    ")
  public actual abstract fun findLiveDataByUid(cjUid: Long): LiveData<ContentJob?>

  @Query(`value` =
      "\n        UPDATE ContentJob\n           SET toUri = :toUri\n         WHERE cjUid = :cjUid\n    ")
  public actual abstract suspend fun updateDestinationDir(cjUid: Long, toUri: String): Unit

  @Query(`value` =
      "\n        SELECT COALESCE((SELECT ContentJob.cjIsMeteredAllowed\n          FROM ContentJob\n         WHERE cjUid = :contentJobId\n         LIMIT 1), 0)\n    ")
  public actual abstract fun findMeteredAllowedLiveData(contentJobId: Long): LiveData<Boolean>

  @Query(`value` =
      "\n        UPDATE ContentJob \n           SET cjIsMeteredAllowed = :meteredAllowed\n         WHERE cjUid IN (SELECT cjiJobUid \n                           FROM ContentJobItem\n                          WHERE cjiContentEntryUid = :contentEntryUid\n                             OR cjiParentContentEntryUid = :contentEntryUid)\n    ")
  public actual abstract suspend fun updateMeteredAllowedForEntry(contentEntryUid: Long,
      meteredAllowed: Boolean): Unit

  @Query(`value` =
      "\n          WITH ConnectivityStateCte(state) AS \n             (SELECT COALESCE(\n                     (SELECT connectivityState \n                        FROM ConnectivityStatus \n                       LIMIT 1), 0))\n   \n           SELECT COALESCE((\n                  SELECT 1 \n                    FROM ContentJob \n                   WHERE cjUid = :jobId\n                    AND ((cjIsMeteredAllowed \n                         AND (SELECT state FROM ConnectivityStateCte) = 3)\n\t\t\t             OR (SELECT state FROM ConnectivityStateCte) = 4)\n                  ) ,0)\n    ")
  public actual abstract suspend fun isConnectivityAcceptableForJob(jobId: Long): Boolean
}
