package com.ustadmobile.core.db.dao

import com.ustadmobile.core.db.dao.xapi.StatementDao
import com.ustadmobile.door.DoorConstants
import com.ustadmobile.door.ext.doorWrapper
import com.ustadmobile.door.ext.doorWrapperNodeId
import com.ustadmobile.door.ext.requirePagingSourceLoadParams
import com.ustadmobile.door.http.DoorHttpServerConfig
import com.ustadmobile.door.http.DoorJsonRequest
import com.ustadmobile.door.http.DoorJsonResponse
import com.ustadmobile.door.log.DoorLogLevel
import com.ustadmobile.door.message.DoorMessage
import com.ustadmobile.door.paging.loadPageDataForHttp
import com.ustadmobile.door.replication.DoorReplicationEntity
import com.ustadmobile.lib.db.entities.ContentEntry
import com.ustadmobile.lib.db.entities.ContentEntryParentChildJoin
import com.ustadmobile.lib.db.entities.ContentEntryPicture2
import com.ustadmobile.lib.db.entities.ContentEntryVersion
import com.ustadmobile.lib.db.entities.xapi.StatementEntity
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.Suppress
import kotlin.collections.buildList
import kotlinx.coroutines.flow.first
import kotlinx.serialization.builtins.nullable
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.json.jsonObject

@Suppress("LocalVariableName", "RedundantSuppression", "FunctionName",
    "RedundantVisibilityModifier")
public suspend
    fun ContentEntryDao.findByUidWithEditDetails_DoorHttp(serverConfig: DoorHttpServerConfig,
    request: DoorJsonRequest): DoorJsonResponse {
  val json = serverConfig.json
  val _arg_uid : Long = request.queryParam("uid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _result_findByUidWithEditDetails = findByUidWithEditDetails(
    uid = _arg_uid,
  )
  val replicationEntities = buildList<DoorReplicationEntity> {
    _result_findByUidWithEditDetails?.entry?.also {
      _row -> 
      add(
        DoorReplicationEntity(tableId = 42,
          orUid = 0,
          entity = json.encodeToJsonElement(ContentEntry.serializer(), _row).jsonObject,
        )
      )
    }
    _result_findByUidWithEditDetails?.picture?.also {
      _row -> 
      add(
        DoorReplicationEntity(tableId = 6_678,
          orUid = 0,
          entity = json.encodeToJsonElement(ContentEntryPicture2.serializer(), _row).jsonObject,
        )
      )
    }
  }
  val _thisNodeId = request.db.doorWrapperNodeId
  return DoorJsonResponse(
    headers = buildList {
      add(Pair(DoorConstants.HEADER_NODE_ID, _thisNodeId.toString()))
    }
    ,
    bodyText = json.encodeToString(
      DoorMessage.serializer(),
      DoorMessage(
        what = DoorMessage.WHAT_REPLICATION_PULL,
        fromNode = _thisNodeId,
        toNode = request.requireNodeId(),
        replications = replicationEntities,
      )
    )
  )
}

@Suppress("LocalVariableName", "RedundantSuppression", "FunctionName",
    "RedundantVisibilityModifier")
public suspend
    fun ContentEntryDao.findByContentEntryUidWithDetailsAsFlow_DoorHttp(serverConfig: DoorHttpServerConfig,
    request: DoorJsonRequest): DoorJsonResponse {
  val json = serverConfig.json
  val _arg_contentEntryUid : Long = request.queryParam("contentEntryUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_clazzUid : Long = request.queryParam("clazzUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_courseBlockUid : Long = request.queryParam("courseBlockUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_accountPersonUid : Long = request.queryParam("accountPersonUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _result_findByContentEntryUidWithDetailsAsFlow = findByContentEntryUidWithDetailsAsFlow(
    contentEntryUid = _arg_contentEntryUid,
    clazzUid = _arg_clazzUid,
    courseBlockUid = _arg_courseBlockUid,
    accountPersonUid = _arg_accountPersonUid,
  ).first()
  val _result_findStatusStatementsByContentEntryUid =
      request.db.doorWrapper.getDaoByClass(StatementDao::class).findStatusStatementsByContentEntryUid(
    contentEntryUid = _arg_contentEntryUid,
    courseBlockUid = _arg_courseBlockUid,
    accountPersonUid = _arg_accountPersonUid,
  )
  val replicationEntities = buildList<DoorReplicationEntity> {
    _result_findByContentEntryUidWithDetailsAsFlow?.entry?.also {
      _row -> 
      add(
        DoorReplicationEntity(tableId = 42,
          orUid = 0,
          entity = json.encodeToJsonElement(ContentEntry.serializer(), _row).jsonObject,
        )
      )
    }
    _result_findByContentEntryUidWithDetailsAsFlow?.latestVersion?.also {
      _row -> 
      add(
        DoorReplicationEntity(tableId = 738,
          orUid = 0,
          entity = json.encodeToJsonElement(ContentEntryVersion.serializer(), _row).jsonObject,
        )
      )
    }
    _result_findByContentEntryUidWithDetailsAsFlow?.picture?.also {
      _row -> 
      add(
        DoorReplicationEntity(tableId = 6_678,
          orUid = 0,
          entity = json.encodeToJsonElement(ContentEntryPicture2.serializer(), _row).jsonObject,
        )
      )
    }
    addAll(
      _result_findStatusStatementsByContentEntryUid.map {
        _row ->
        DoorReplicationEntity(tableId = 60,
          orUid = 0,
          entity = json.encodeToJsonElement(StatementEntity.serializer(), _row).jsonObject,
        )
      }
    )
  }
  val _thisNodeId = request.db.doorWrapperNodeId
  return DoorJsonResponse(
    headers = buildList {
      add(Pair(DoorConstants.HEADER_NODE_ID, _thisNodeId.toString()))
    }
    ,
    bodyText = json.encodeToString(
      DoorMessage.serializer(),
      DoorMessage(
        what = DoorMessage.WHAT_REPLICATION_PULL,
        fromNode = _thisNodeId,
        toNode = request.requireNodeId(),
        replications = replicationEntities,
      )
    )
  )
}

@Suppress("LocalVariableName", "RedundantSuppression", "FunctionName",
    "RedundantVisibilityModifier")
public suspend fun ContentEntryDao.findTitleByUidAsync_DoorHttp(serverConfig: DoorHttpServerConfig,
    request: DoorJsonRequest): DoorJsonResponse {
  val json = serverConfig.json
  val _arg_entryUid : Long = request.queryParam("entryUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _result_findByUidAsync = findByUidAsync(
    entryUid = _arg_entryUid,
  )
  val replicationEntities = buildList<DoorReplicationEntity> {
    _result_findByUidAsync?.also {
      _row -> 
      add(
        DoorReplicationEntity(tableId = 42,
          orUid = 0,
          entity = json.encodeToJsonElement(ContentEntry.serializer(), _row).jsonObject,
        )
      )
    }
  }
  val _thisNodeId = request.db.doorWrapperNodeId
  return DoorJsonResponse(
    headers = buildList {
      add(Pair(DoorConstants.HEADER_NODE_ID, _thisNodeId.toString()))
    }
    ,
    bodyText = json.encodeToString(
      DoorMessage.serializer(),
      DoorMessage(
        what = DoorMessage.WHAT_REPLICATION_PULL,
        fromNode = _thisNodeId,
        toNode = request.requireNodeId(),
        replications = replicationEntities,
      )
    )
  )
}

@Suppress("LocalVariableName", "RedundantSuppression", "FunctionName",
    "RedundantVisibilityModifier")
public suspend
    fun ContentEntryDao.getChildrenByParentUidWithCategoryFilterOrderByName_DoorHttp(serverConfig: DoorHttpServerConfig,
    request: DoorJsonRequest): DoorJsonResponse {
  val json = serverConfig.json
  val _arg_accountPersonUid : Long = request.queryParam("accountPersonUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_parentUid : Long = request.queryParam("parentUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_langParam : Long = request.queryParam("langParam")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_categoryParam0 : Long = request.queryParam("categoryParam0")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_sortOrder : Int = request.queryParam("sortOrder")?.let {
    json.decodeFromString(Int.serializer(), it)
  } ?: 0
  val _arg_includeDeleted : Boolean = request.queryParam("includeDeleted")?.let {
    json.decodeFromString(Boolean.serializer(), it)
  } ?: false
  val _pagingLoadParams = request.requirePagingSourceLoadParams(
    json = json,
    keyDeserializationStrategy = Int.serializer().nullable,
  )

  val _result_getChildrenByParentUidWithCategoryFilterOrderByName_pagingSource =
      getChildrenByParentUidWithCategoryFilterOrderByName(
    accountPersonUid = _arg_accountPersonUid,
    parentUid = _arg_parentUid,
    langParam = _arg_langParam,
    categoryParam0 = _arg_categoryParam0,
    sortOrder = _arg_sortOrder,
    includeDeleted = true,
  ).loadPageDataForHttp(_pagingLoadParams)
  val _result_getChildrenByParentUidWithCategoryFilterOrderByName =
      _result_getChildrenByParentUidWithCategoryFilterOrderByName_pagingSource.data
  serverConfig.logger.log(DoorLogLevel.VERBOSE,
      "DoorPaging: loaded from: ${_pagingLoadParams.key} endOfPaginationReached=${_result_getChildrenByParentUidWithCategoryFilterOrderByName_pagingSource.endOfPaginationReached}")
  val _endOfPaginationReached =
      _result_getChildrenByParentUidWithCategoryFilterOrderByName_pagingSource.endOfPaginationReached

  val _result_findListOfChildsByParentUuid =
      request.db.doorWrapper.getDaoByClass(ContentEntryParentChildJoinDao::class).findListOfChildsByParentUuid(
    parentUid = _arg_parentUid,
  )
  val _result_findStatusStatementByParentContentEntryUid =
      request.db.doorWrapper.getDaoByClass(StatementDao::class).findStatusStatementByParentContentEntryUid(
    parentUid = _arg_parentUid,
    accountPersonUid = _arg_accountPersonUid,
  )
  val replicationEntities = buildList<DoorReplicationEntity> {
    addAll(
      _result_getChildrenByParentUidWithCategoryFilterOrderByName.mapNotNull {
        _row ->
        _row.contentEntry?.let {
          DoorReplicationEntity(tableId = 42,
            orUid = 0,
            entity = json.encodeToJsonElement(ContentEntry.serializer(), it).jsonObject,
          )
        }

      }
    )
    addAll(
      _result_getChildrenByParentUidWithCategoryFilterOrderByName.mapNotNull {
        _row ->
        _row.picture?.let {
          DoorReplicationEntity(tableId = 6_678,
            orUid = 0,
            entity = json.encodeToJsonElement(ContentEntryPicture2.serializer(), it).jsonObject,
          )
        }

      }
    )
    addAll(
      _result_getChildrenByParentUidWithCategoryFilterOrderByName.mapNotNull {
        _row ->
        _row.contentEntryParentChildJoin?.let {
          DoorReplicationEntity(tableId = 7,
            orUid = 0,
            entity = json.encodeToJsonElement(ContentEntryParentChildJoin.serializer(),
                it).jsonObject,
          )
        }

      }
    )
    addAll(
      _result_findListOfChildsByParentUuid.map {
        _row ->
        DoorReplicationEntity(tableId = 7,
          orUid = 0,
          entity = json.encodeToJsonElement(ContentEntryParentChildJoin.serializer(),
              _row).jsonObject,
        )
      }
    )
    addAll(
      _result_findStatusStatementByParentContentEntryUid.map {
        _row ->
        DoorReplicationEntity(tableId = 60,
          orUid = 0,
          entity = json.encodeToJsonElement(StatementEntity.serializer(), _row).jsonObject,
        )
      }
    )
  }
  val _thisNodeId = request.db.doorWrapperNodeId
  return DoorJsonResponse(
    headers = buildList {
      add(Pair(DoorConstants.HEADER_NODE_ID, _thisNodeId.toString()))
      add(Pair(DoorConstants.HEADER_PAGING_END_REACHED, _endOfPaginationReached.toString()))
    }
    ,
    bodyText = json.encodeToString(
      DoorMessage.serializer(),
      DoorMessage(
        what = DoorMessage.WHAT_REPLICATION_PULL,
        fromNode = _thisNodeId,
        toNode = request.requireNodeId(),
        replications = replicationEntities,
      )
    )
  )
}
