package com.ustadmobile.core.db.dao

import com.ustadmobile.door.DoorConstants
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.CoursePicture
import com.ustadmobile.lib.db.entities.EnrolmentRequest
import com.ustadmobile.lib.db.entities.Person
import com.ustadmobile.lib.db.entities.PersonPicture
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.String
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 EnrolmentRequestDao.hasPendingRequests_DoorHttp(serverConfig: DoorHttpServerConfig,
    request: DoorJsonRequest): DoorJsonResponse {
  val json = serverConfig.json
  val _arg_personUid : Long = request.queryParam("personUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_clazzUid : Long = request.queryParam("clazzUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _result_findByClazzAndPerson = findByClazzAndPerson(
    personUid = _arg_personUid,
    clazzUid = _arg_clazzUid,
    statusFilter = 1,
  )
  val replicationEntities = buildList<DoorReplicationEntity> {
    addAll(
      _result_findByClazzAndPerson.map {
        _row ->
        DoorReplicationEntity(tableId = 10_070,
          orUid = 0,
          entity = json.encodeToJsonElement(EnrolmentRequest.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 EnrolmentRequestDao.findRequestsForUserAsFlow_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_statusFilter : Int = request.queryParam("statusFilter")?.let {
    json.decodeFromString(Int.serializer(), it)
  } ?: 0
  val _result_findRequestsForUserAsFlow = findRequestsForUserAsFlow(
    accountPersonUid = _arg_accountPersonUid,
    statusFilter = 0,
  ).first()
  val replicationEntities = buildList<DoorReplicationEntity> {
    addAll(
      _result_findRequestsForUserAsFlow.mapNotNull {
        _row ->
        _row.enrolmentRequest?.let {
          DoorReplicationEntity(tableId = 10_070,
            orUid = 0,
            entity = json.encodeToJsonElement(EnrolmentRequest.serializer(), it).jsonObject,
          )
        }

      }
    )
    addAll(
      _result_findRequestsForUserAsFlow.mapNotNull {
        _row ->
        _row.coursePicture?.let {
          DoorReplicationEntity(tableId = 125,
            orUid = 0,
            entity = json.encodeToJsonElement(CoursePicture.serializer(), it).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 EnrolmentRequestDao.findPendingEnrolmentsForCourse_DoorHttp(serverConfig: DoorHttpServerConfig,
    request: DoorJsonRequest): DoorJsonResponse {
  val json = serverConfig.json
  val _arg_clazzUid : Long = request.queryParam("clazzUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_includeDeleted : Boolean = request.queryParam("includeDeleted")?.let {
    json.decodeFromString(Boolean.serializer(), it)
  } ?: false
  val _arg_statusFilter : Int = request.queryParam("statusFilter")?.let {
    json.decodeFromString(Int.serializer(), it)
  } ?: 0
  val _arg_searchText : String = request.queryParam("searchText")?.let {
    json.decodeFromString(String.serializer(), it)
  } ?: ""
  val _arg_sortOrder : Int = request.queryParam("sortOrder")?.let {
    json.decodeFromString(Int.serializer(), it)
  } ?: 0
  val _pagingLoadParams = request.requirePagingSourceLoadParams(
    json = json,
    keyDeserializationStrategy = Int.serializer().nullable,
  )

  val _result_findPendingEnrolmentsForCourse_pagingSource = findPendingEnrolmentsForCourse(
    clazzUid = _arg_clazzUid,
    includeDeleted = true,
    statusFilter = 0,
    searchText = _arg_searchText,
    sortOrder = _arg_sortOrder,
  ).loadPageDataForHttp(_pagingLoadParams)
  val _result_findPendingEnrolmentsForCourse =
      _result_findPendingEnrolmentsForCourse_pagingSource.data
  serverConfig.logger.log(DoorLogLevel.VERBOSE,
      "DoorPaging: loaded from: ${_pagingLoadParams.key} endOfPaginationReached=${_result_findPendingEnrolmentsForCourse_pagingSource.endOfPaginationReached}")
  val _endOfPaginationReached =
      _result_findPendingEnrolmentsForCourse_pagingSource.endOfPaginationReached

  val replicationEntities = buildList<DoorReplicationEntity> {
    addAll(
      _result_findPendingEnrolmentsForCourse.mapNotNull {
        _row ->
        _row.enrolmentRequest?.let {
          DoorReplicationEntity(tableId = 10_070,
            orUid = 0,
            entity = json.encodeToJsonElement(EnrolmentRequest.serializer(), it).jsonObject,
          )
        }

      }
    )
    addAll(
      _result_findPendingEnrolmentsForCourse.mapNotNull {
        _row ->
        _row.personPicture?.let {
          DoorReplicationEntity(tableId = 50,
            orUid = 0,
            entity = json.encodeToJsonElement(PersonPicture.serializer(), it).jsonObject,
          )
        }

      }
    )
    addAll(
      _result_findPendingEnrolmentsForCourse.mapNotNull {
        _row ->
        _row.person?.let {
          DoorReplicationEntity(tableId = 9,
            orUid = 0,
            entity = json.encodeToJsonElement(Person.serializer(), it).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,
      )
    )
  )
}
