package com.ustadmobile.libcache.db

import androidx.room.DatabaseConfiguration
import androidx.sqlite.db.SupportSQLiteOpenHelper
import com.ustadmobile.door.DoorDatabaseWrapper
import com.ustadmobile.door.log.DoorLogger
import com.ustadmobile.door.message.DoorMessageCallback
import com.ustadmobile.door.nodeevent.NodeEventManagerAndroid
import com.ustadmobile.door.nodeevent.NodeEventManagerCommon
import com.ustadmobile.door.room.RoomDatabase
import com.ustadmobile.door.util.makeDummyInvalidationHandler
import com.ustadmobile.libcache.db.dao.CacheEntryDao
import com.ustadmobile.libcache.db.dao.RequestedEntryDao
import com.ustadmobile.libcache.db.dao.RetentionLockDao
import kotlin.Any
import kotlin.IllegalArgumentException
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.reflect.KClass
import kotlinx.coroutines.Runnable
import androidx.room.InvalidationTracker as AndroidxRoomInvalidationTracker
import com.ustadmobile.door.room.InvalidationTracker as DoorRoomInvalidationTracker

@Suppress("REDUNDANT_PROJECTION", "ClassName")
public class UstadCacheDb_DoorWrapper(
  private val _db: UstadCacheDb,
  override val nodeId: Long,
  private val messageCallback: DoorMessageCallback<UstadCacheDb>,
  logger: DoorLogger,
  dbName: String,
) : UstadCacheDb(), DoorDatabaseWrapper<UstadCacheDb> {
  override val dbName: String
    get() = "DoorWrapper for [${_db.toString()}]"

  override val cacheEntryDao: CacheEntryDao
    get() = _db.cacheEntryDao

  override val requestedEntryDao: RequestedEntryDao
    get() = _db.requestedEntryDao

  override val retentionLockDao: RetentionLockDao
    get() = _db.retentionLockDao

  override val realDatabase: RoomDatabase
    get() = _db

  override val nodeEventManager: NodeEventManagerCommon<UstadCacheDb> = NodeEventManagerAndroid(_db,
      messageCallback, logger, dbName)


  override val invalidationTracker: DoorRoomInvalidationTracker
    get() = _db.invalidationTracker

  override fun clearAllTables() {
    _db.clearAllTables()
  }

  override fun runInTransaction(runnable: Runnable) {
    _db.runInTransaction(runnable)
  }

  protected override fun createOpenHelper(config: DatabaseConfiguration): SupportSQLiteOpenHelper =
      throw IllegalAccessException("Cannot use open helper on repository")

  protected override fun createInvalidationTracker(): AndroidxRoomInvalidationTracker =
      makeDummyInvalidationHandler()

  @Suppress("UNCHECKED_CAST")
  override fun <T : Any> getDaoByClass(daoClass: KClass<T>): T = when(daoClass) {
    CacheEntryDao::class -> cacheEntryDao as T
    RequestedEntryDao::class -> requestedEntryDao as T
    RetentionLockDao::class -> retentionLockDao as T
    else -> throw IllegalArgumentException("No such DAO on this DB")
  }

  override fun close() {
    _db.close()
  }
}
