package com.ustadmobile.core.db.dao

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

@Dao
public actual abstract class ScrapeQueueItemDao : BaseDao<ScrapeQueueItem> {
  @Query(`value` =
      "SELECT * FROM ScrapeQueueItem WHERE status = 1 AND itemType = :itemType ORDER BY priority ASC LIMIT 10")
  public actual abstract fun findNextQueueItems(itemType: Int): LiveData<List<ScrapeQueueItem>>

  @Query(`value` =
      "UPDATE ScrapeQueueItem SET status = :status, errorCode = :errorCode WHERE sqiUid = :uid")
  public actual abstract fun updateSetStatusById(
    uid: Int,
    status: Int,
    errorCode: Int,
  ): Unit

  @Query(`value` =
      "SELECT * from ScrapeQueueItem WHERE runId = :runId AND scrapeUrl = :indexUrl LIMIT 1")
  public actual abstract fun getExistingQueueItem(runId: Int, indexUrl: String): ScrapeQueueItem?

  @Query(`value` =
      "SELECT * from ScrapeQueueItem WHERE runId = :runId AND sqiContentEntryUid = :entryUid LIMIT 1")
  public actual abstract fun findExistingQueueItem(runId: Int, entryUid: Long): ScrapeQueueItem?

  @Query(`value` = "UPDATE ScrapeQueueItem SET timeStarted = :timeStarted WHERE sqiUid = :uid")
  public actual abstract fun setTimeStarted(uid: Int, timeStarted: Long): Unit

  @Query(`value` = "UPDATE ScrapeQueueItem SET timeFinished = :timeFinished WHERE sqiUid = :uid")
  public actual abstract fun setTimeFinished(uid: Int, timeFinished: Long): Unit

  @Query(`value` =
      "SELECT ScrapeQueueItem.*, ScrapeRun.* FROM ScrapeQueueItem \n                    LEFT JOIN ScrapeRun ON  ScrapeQueueItem.runId = ScrapeRun.scrapeRunUid\n                    WHERE ScrapeQueueItem.sqiUid = :sqiUid")
  public actual abstract fun findByUid(sqiUid: Int): ScrapeQueueItemWithScrapeRun?
}
