package com.ustadmobile.core.db.dao

import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Query
import com.ustadmobile.lib.db.entities.ContainerImportJob
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Unit
import kotlin.collections.List

@Dao
public actual abstract class ContainerImportJobDao : BaseDao<ContainerImportJob> {
  @Query(`value` = "SELECT * FROM ContainerImportJob WHERE cijSessionId = :sessionId")
  public actual abstract fun findBySessionId(sessionId: String): ContainerImportJob?

  @Query(`value` = "SELECT * FROM ContainerImportJob where cijUid = :uploadId")
  public actual abstract fun findByUid(uploadId: Long): ContainerImportJob?

  @Query(`value` =
      "\n            SELECT * \n              FROM ContainerImportJob \n             WHERE cijJobStatus = 4\n                   AND (NOT cijImportCompleted OR \n                   (SELECT connectivityState \n                      FROM ConnectivityStatus)\n                   IN (3, 4))\n             LIMIT 10")
  public actual abstract fun findJobs(): LiveData<List<ContainerImportJob>>

  @Query(`value` =
      "UPDATE ContainerImportJob SET cijJobStatus = 4 WHERE cijUid = :uploadJobId AND cijJobStatus = 0")
  public actual abstract suspend fun setStatusToQueueAsync(uploadJobId: Long): Unit

  @Query(`value` =
      "UPDATE ContainerImportJob SET cijBytesSoFar = :progress, cijContentLength = :contentLength WHERE cijUid = :uploadJobId")
  public actual abstract fun updateProgress(
    progress: Long,
    contentLength: Long,
    uploadJobId: Long,
  ): Unit

  @Query(`value` =
      "UPDATE ContainerImportJob SET cijJobStatus = :status WHERE cijUid = :uploadJobId")
  public actual abstract fun updateStatus(status: Int, uploadJobId: Long): Unit

  @Query(`value` =
      "UPDATE ContainerImportJob \n                       SET cijImportCompleted = :importCompleted,\n                           cijContainerUid = :containerUid\n                     WHERE cijUid = :importJobUid")
  public actual abstract fun updateImportComplete(
    importCompleted: Boolean,
    containerUid: Long,
    importJobUid: Long,
  ): Unit

  @Query(`value` =
      "SELECT ContentEntry.title FROM ContainerImportJob LEFT JOIN ContentEntry ON ContainerImportJob.cijContentEntryUid = ContentEntry.contentEntryUid WHERE ContainerImportJob.cijUid = :importJobUid")
  public actual abstract suspend fun getTitleOfEntry(importJobUid: Long): String?

  @Query(`value` =
      "SELECT * From  ContainerImportJob WHERE ContainerImportJob.cijUid = :importJobUid")
  public actual abstract fun getImportJobLiveData(importJobUid: Long): LiveData<ContainerImportJob?>

  @Query(`value` =
      "UPDATE ContainerImportJob SET cijSessionId = :sessionId WHERE cijUid = :importJobUid")
  public actual abstract suspend fun updateSessionId(importJobUid: Long, sessionId: String): Unit
}
