package world.respect.datalayer.db.school.daos

import androidx.room.EntityInsertAdapter
import androidx.room.RoomDatabase
import androidx.room.coroutines.createFlow
import androidx.room.util.appendPlaceholders
import androidx.room.util.getColumnIndexOrThrow
import androidx.room.util.performSuspending
import androidx.sqlite.SQLiteStatement
import javax.`annotation`.processing.Generated
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.collections.List
import kotlin.collections.MutableList
import kotlin.collections.mutableListOf
import kotlin.reflect.KClass
import kotlin.text.StringBuilder
import kotlin.time.Instant
import kotlinx.coroutines.flow.Flow
import world.respect.datalayer.db.school.SchoolTypeConverters
import world.respect.datalayer.db.school.entities.LastModifiedAndPermission
import world.respect.datalayer.db.school.entities.SchoolConfigSettingEntity
import world.respect.datalayer.db.shared.SharedConverters
import world.respect.datalayer.school.model.StatusEnum

@Generated(value = ["androidx.room.RoomProcessor"])
@Suppress(names = ["UNCHECKED_CAST", "DEPRECATION", "REDUNDANT_PROJECTION", "REMOVAL"])
public class SchoolConfigSettingEntityDao_Impl(
  __db: RoomDatabase,
) : SchoolConfigSettingEntityDao {
  private val __db: RoomDatabase

  private val __insertAdapterOfSchoolConfigSettingEntity:
      EntityInsertAdapter<SchoolConfigSettingEntity>

  private val __schoolTypeConverters: SchoolTypeConverters = SchoolTypeConverters()

  private val __sharedConverters: SharedConverters = SharedConverters()
  init {
    this.__db = __db
    this.__insertAdapterOfSchoolConfigSettingEntity = object : EntityInsertAdapter<SchoolConfigSettingEntity>() {
      protected override fun createQuery(): String = "INSERT OR REPLACE INTO `SchoolConfigSettingEntity` (`scsKey`,`scsValue`,`scsStatus`,`scsLastModified`,`scsStored`,`scsCanReadFlags`,`scsAnonCanRead`,`scsCanWriteFlags`) VALUES (?,?,?,?,?,?,?,?)"

      protected override fun bind(statement: SQLiteStatement, entity: SchoolConfigSettingEntity) {
        statement.bindText(1, entity.scsKey)
        statement.bindText(2, entity.scsValue)
        val _tmp: Int = __schoolTypeConverters.fromStatusEnum(entity.scsStatus)
        statement.bindLong(3, _tmp.toLong())
        val _tmp_1: Long? = __sharedConverters.fromInstant(entity.scsLastModified)
        if (_tmp_1 == null) {
          statement.bindNull(4)
        } else {
          statement.bindLong(4, _tmp_1)
        }
        val _tmp_2: Long? = __sharedConverters.fromInstant(entity.scsStored)
        if (_tmp_2 == null) {
          statement.bindNull(5)
        } else {
          statement.bindLong(5, _tmp_2)
        }
        statement.bindLong(6, entity.scsCanReadFlags.toLong())
        val _tmp_3: Int = if (entity.scsAnonCanRead) 1 else 0
        statement.bindLong(7, _tmp_3.toLong())
        statement.bindLong(8, entity.scsCanWriteFlags.toLong())
      }
    }
  }

  public override suspend fun insert(entities: List<SchoolConfigSettingEntity>): Unit = performSuspending(__db, false, true) { _connection ->
    __insertAdapterOfSchoolConfigSettingEntity.insert(_connection, entities)
  }

  public override fun listAsFlow(
    authenticatedPersonUidNum: Long,
    keys: List<String>?,
    since: Long,
  ): Flow<List<SchoolConfigSettingEntity>> {
    val _stringBuilder: StringBuilder = StringBuilder()
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("            SELECT SchoolConfigSettingEntity.*")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("              FROM SchoolConfigSettingEntity")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("             WHERE scsKey IN (")
    val _inputSize: Int = if (keys == null) 1 else keys.size
    appendPlaceholders(_stringBuilder, _inputSize)
    _stringBuilder.append(")")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("             AND SchoolConfigSettingEntity.scsStored > ")
    _stringBuilder.append("?")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("             AND (")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("            scsAnonCanRead OR ((")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("            SELECT PersonRoleEntity.prRoleEnum")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("              FROM PersonRoleEntity")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("             WHERE PersonRoleEntity.prPersonGuidHash = ")
    _stringBuilder.append("?")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("             LIMIT 1")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("        ) & scsCanReadFlags) > 0")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("        )")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("        ")
    val _sql: String = _stringBuilder.toString()
    return createFlow(__db, false, arrayOf("SchoolConfigSettingEntity", "PersonRoleEntity")) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        if (keys == null) {
          _stmt.bindNull(_argIndex)
        } else {
          for (_item: String in keys) {
            _stmt.bindText(_argIndex, _item)
            _argIndex++
          }
        }
        _argIndex = 1 + _inputSize
        _stmt.bindLong(_argIndex, since)
        _argIndex = 2 + _inputSize
        _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
        val _columnIndexOfScsKey: Int = getColumnIndexOrThrow(_stmt, "scsKey")
        val _columnIndexOfScsValue: Int = getColumnIndexOrThrow(_stmt, "scsValue")
        val _columnIndexOfScsStatus: Int = getColumnIndexOrThrow(_stmt, "scsStatus")
        val _columnIndexOfScsLastModified: Int = getColumnIndexOrThrow(_stmt, "scsLastModified")
        val _columnIndexOfScsStored: Int = getColumnIndexOrThrow(_stmt, "scsStored")
        val _columnIndexOfScsCanReadFlags: Int = getColumnIndexOrThrow(_stmt, "scsCanReadFlags")
        val _columnIndexOfScsAnonCanRead: Int = getColumnIndexOrThrow(_stmt, "scsAnonCanRead")
        val _columnIndexOfScsCanWriteFlags: Int = getColumnIndexOrThrow(_stmt, "scsCanWriteFlags")
        val _result: MutableList<SchoolConfigSettingEntity> = mutableListOf()
        while (_stmt.step()) {
          val _item_1: SchoolConfigSettingEntity
          val _tmpScsKey: String
          _tmpScsKey = _stmt.getText(_columnIndexOfScsKey)
          val _tmpScsValue: String
          _tmpScsValue = _stmt.getText(_columnIndexOfScsValue)
          val _tmpScsStatus: StatusEnum
          val _tmp: Int
          _tmp = _stmt.getLong(_columnIndexOfScsStatus).toInt()
          _tmpScsStatus = __schoolTypeConverters.toStatusEnum(_tmp)
          val _tmpScsLastModified: Instant
          val _tmp_1: Long?
          if (_stmt.isNull(_columnIndexOfScsLastModified)) {
            _tmp_1 = null
          } else {
            _tmp_1 = _stmt.getLong(_columnIndexOfScsLastModified)
          }
          val _tmp_2: Instant? = __sharedConverters.toInstant(_tmp_1)
          if (_tmp_2 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpScsLastModified = _tmp_2
          }
          val _tmpScsStored: Instant
          val _tmp_3: Long?
          if (_stmt.isNull(_columnIndexOfScsStored)) {
            _tmp_3 = null
          } else {
            _tmp_3 = _stmt.getLong(_columnIndexOfScsStored)
          }
          val _tmp_4: Instant? = __sharedConverters.toInstant(_tmp_3)
          if (_tmp_4 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpScsStored = _tmp_4
          }
          val _tmpScsCanReadFlags: Int
          _tmpScsCanReadFlags = _stmt.getLong(_columnIndexOfScsCanReadFlags).toInt()
          val _tmpScsAnonCanRead: Boolean
          val _tmp_5: Int
          _tmp_5 = _stmt.getLong(_columnIndexOfScsAnonCanRead).toInt()
          _tmpScsAnonCanRead = _tmp_5 != 0
          val _tmpScsCanWriteFlags: Int
          _tmpScsCanWriteFlags = _stmt.getLong(_columnIndexOfScsCanWriteFlags).toInt()
          _item_1 = SchoolConfigSettingEntity(_tmpScsKey,_tmpScsValue,_tmpScsStatus,_tmpScsLastModified,_tmpScsStored,_tmpScsCanReadFlags,_tmpScsAnonCanRead,_tmpScsCanWriteFlags)
          _result.add(_item_1)
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  public override suspend fun list(
    authenticatedPersonUidNum: Long,
    keys: List<String>?,
    since: Long,
  ): List<SchoolConfigSettingEntity> {
    val _stringBuilder: StringBuilder = StringBuilder()
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("            SELECT SchoolConfigSettingEntity.*")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("              FROM SchoolConfigSettingEntity")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("             WHERE scsKey IN (")
    val _inputSize: Int = if (keys == null) 1 else keys.size
    appendPlaceholders(_stringBuilder, _inputSize)
    _stringBuilder.append(")")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("             AND SchoolConfigSettingEntity.scsStored > ")
    _stringBuilder.append("?")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("             AND (")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("            scsAnonCanRead OR ((")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("            SELECT PersonRoleEntity.prRoleEnum")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("              FROM PersonRoleEntity")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("             WHERE PersonRoleEntity.prPersonGuidHash = ")
    _stringBuilder.append("?")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("             LIMIT 1")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("        ) & scsCanReadFlags) > 0")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("        )")
    _stringBuilder.append("""
        |
        |""".trimMargin())
    _stringBuilder.append("        ")
    val _sql: String = _stringBuilder.toString()
    return performSuspending(__db, true, false) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        if (keys == null) {
          _stmt.bindNull(_argIndex)
        } else {
          for (_item: String in keys) {
            _stmt.bindText(_argIndex, _item)
            _argIndex++
          }
        }
        _argIndex = 1 + _inputSize
        _stmt.bindLong(_argIndex, since)
        _argIndex = 2 + _inputSize
        _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
        val _columnIndexOfScsKey: Int = getColumnIndexOrThrow(_stmt, "scsKey")
        val _columnIndexOfScsValue: Int = getColumnIndexOrThrow(_stmt, "scsValue")
        val _columnIndexOfScsStatus: Int = getColumnIndexOrThrow(_stmt, "scsStatus")
        val _columnIndexOfScsLastModified: Int = getColumnIndexOrThrow(_stmt, "scsLastModified")
        val _columnIndexOfScsStored: Int = getColumnIndexOrThrow(_stmt, "scsStored")
        val _columnIndexOfScsCanReadFlags: Int = getColumnIndexOrThrow(_stmt, "scsCanReadFlags")
        val _columnIndexOfScsAnonCanRead: Int = getColumnIndexOrThrow(_stmt, "scsAnonCanRead")
        val _columnIndexOfScsCanWriteFlags: Int = getColumnIndexOrThrow(_stmt, "scsCanWriteFlags")
        val _result: MutableList<SchoolConfigSettingEntity> = mutableListOf()
        while (_stmt.step()) {
          val _item_1: SchoolConfigSettingEntity
          val _tmpScsKey: String
          _tmpScsKey = _stmt.getText(_columnIndexOfScsKey)
          val _tmpScsValue: String
          _tmpScsValue = _stmt.getText(_columnIndexOfScsValue)
          val _tmpScsStatus: StatusEnum
          val _tmp: Int
          _tmp = _stmt.getLong(_columnIndexOfScsStatus).toInt()
          _tmpScsStatus = __schoolTypeConverters.toStatusEnum(_tmp)
          val _tmpScsLastModified: Instant
          val _tmp_1: Long?
          if (_stmt.isNull(_columnIndexOfScsLastModified)) {
            _tmp_1 = null
          } else {
            _tmp_1 = _stmt.getLong(_columnIndexOfScsLastModified)
          }
          val _tmp_2: Instant? = __sharedConverters.toInstant(_tmp_1)
          if (_tmp_2 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpScsLastModified = _tmp_2
          }
          val _tmpScsStored: Instant
          val _tmp_3: Long?
          if (_stmt.isNull(_columnIndexOfScsStored)) {
            _tmp_3 = null
          } else {
            _tmp_3 = _stmt.getLong(_columnIndexOfScsStored)
          }
          val _tmp_4: Instant? = __sharedConverters.toInstant(_tmp_3)
          if (_tmp_4 == null) {
            error("Expected NON-NULL 'kotlin.time.Instant', but it was NULL.")
          } else {
            _tmpScsStored = _tmp_4
          }
          val _tmpScsCanReadFlags: Int
          _tmpScsCanReadFlags = _stmt.getLong(_columnIndexOfScsCanReadFlags).toInt()
          val _tmpScsAnonCanRead: Boolean
          val _tmp_5: Int
          _tmp_5 = _stmt.getLong(_columnIndexOfScsAnonCanRead).toInt()
          _tmpScsAnonCanRead = _tmp_5 != 0
          val _tmpScsCanWriteFlags: Int
          _tmpScsCanWriteFlags = _stmt.getLong(_columnIndexOfScsCanWriteFlags).toInt()
          _item_1 = SchoolConfigSettingEntity(_tmpScsKey,_tmpScsValue,_tmpScsStatus,_tmpScsLastModified,_tmpScsStored,_tmpScsCanReadFlags,_tmpScsAnonCanRead,_tmpScsCanWriteFlags)
          _result.add(_item_1)
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  public override suspend fun getLastModifiedByKey(key: String): Long? {
    val _sql: String = """
        |
        |        SELECT scsLastModified
        |          FROM SchoolConfigSettingEntity
        |         WHERE scsKey = ?
        |    
        """.trimMargin()
    return performSuspending(__db, true, false) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        _stmt.bindText(_argIndex, key)
        val _result: Long?
        if (_stmt.step()) {
          if (_stmt.isNull(0)) {
            _result = null
          } else {
            _result = _stmt.getLong(0)
          }
        } else {
          _result = null
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  public override suspend fun getLastModifiedAndHasPermission(
    authenticatedPersonUidNum: Long,
    key: String,
    canWriteRolesMask: Int,
  ): LastModifiedAndPermission {
    val _sql: String = """
        |
        |            SELECT 0 AS uidNum,
        |               (SELECT SchoolConfigSettingEntity.scsLastModified
        |                  FROM SchoolConfigSettingEntity
        |                 WHERE SchoolConfigSettingEntity.scsKey = ?) AS lastModified,
        |               (
        |                -- for existing records
        |                EXISTS (
        |                   SELECT 1
        |                     FROM SchoolConfigSettingEntity
        |                    WHERE SchoolConfigSettingEntity.scsKey = ?
        |                      AND (
        |            ((
        |            SELECT PersonRoleEntity.prRoleEnum
        |              FROM PersonRoleEntity
        |             WHERE PersonRoleEntity.prPersonGuidHash = ?
        |             LIMIT 1
        |        ) & scsCanWriteFlags) > 0
        |        )
        |                ) 
        |                OR 
        |                -- for new records (using the passed mask)
        |                (NOT EXISTS (SELECT 1 FROM SchoolConfigSettingEntity WHERE scsKey = ?) 
        |                 AND (
        |            SELECT PersonRoleEntity.prRoleEnum
        |              FROM PersonRoleEntity
        |             WHERE PersonRoleEntity.prPersonGuidHash = ?
        |             LIMIT 1
        |        ) & ? > 0)
        |               ) AS hasPermission
        |        
        """.trimMargin()
    return performSuspending(__db, true, false) { _connection ->
      val _stmt: SQLiteStatement = _connection.prepare(_sql)
      try {
        var _argIndex: Int = 1
        _stmt.bindText(_argIndex, key)
        _argIndex = 2
        _stmt.bindText(_argIndex, key)
        _argIndex = 3
        _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
        _argIndex = 4
        _stmt.bindText(_argIndex, key)
        _argIndex = 5
        _stmt.bindLong(_argIndex, authenticatedPersonUidNum)
        _argIndex = 6
        _stmt.bindLong(_argIndex, canWriteRolesMask.toLong())
        val _columnIndexOfUidNum: Int = 0
        val _columnIndexOfLastModified: Int = 1
        val _columnIndexOfHasPermission: Int = 2
        val _result: LastModifiedAndPermission
        if (_stmt.step()) {
          val _tmpUidNum: Long
          _tmpUidNum = _stmt.getLong(_columnIndexOfUidNum)
          val _tmpLastModified: Long?
          if (_stmt.isNull(_columnIndexOfLastModified)) {
            _tmpLastModified = null
          } else {
            _tmpLastModified = _stmt.getLong(_columnIndexOfLastModified)
          }
          val _tmpHasPermission: Boolean
          val _tmp: Int
          _tmp = _stmt.getLong(_columnIndexOfHasPermission).toInt()
          _tmpHasPermission = _tmp != 0
          _result = LastModifiedAndPermission(_tmpUidNum,_tmpLastModified,_tmpHasPermission)
        } else {
          error("The query result was empty, but expected a single row to return a NON-NULL object of type 'world.respect.datalayer.db.school.entities.LastModifiedAndPermission'.")
        }
        _result
      } finally {
        _stmt.close()
      }
    }
  }

  public companion object {
    public fun getRequiredConverters(): List<KClass<*>> = emptyList()
  }
}
