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.getLimit
import com.ustadmobile.door.paging.getOffset
import com.ustadmobile.door.paging.loadPageDataForHttp
import com.ustadmobile.door.replication.DoorReplicationEntity
import com.ustadmobile.lib.db.entities.ClazzEnrolment
import com.ustadmobile.lib.db.entities.LeavingReason
import com.ustadmobile.lib.db.entities.Person
import com.ustadmobile.lib.db.entities.PersonPicture
import com.ustadmobile.lib.db.entities.xapi.ActorEntity
import com.ustadmobile.lib.db.entities.xapi.GroupMemberActorJoin
import com.ustadmobile.lib.db.entities.xapi.StatementEntity
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.collections.buildList
import kotlinx.serialization.builtins.nullable
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.json.jsonObject

@Suppress("LocalVariableName", "RedundantSuppression", "FunctionName",
    "RedundantVisibilityModifier")
public suspend
    fun ClazzEnrolmentDao.findEnrolmentWithLeavingReason_DoorHttp(serverConfig: DoorHttpServerConfig,
    request: DoorJsonRequest): DoorJsonResponse {
  val json = serverConfig.json
  val _arg_enrolmentUid : Long = request.queryParam("enrolmentUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _result_findEnrolmentWithLeavingReason = findEnrolmentWithLeavingReason(
    enrolmentUid = _arg_enrolmentUid,
  )
  val replicationEntities = buildList<DoorReplicationEntity> {
    _result_findEnrolmentWithLeavingReason?.also {
      _row -> 
      add(
        DoorReplicationEntity(tableId = 65,
          orUid = 0,
          entity = json.encodeToJsonElement(ClazzEnrolment.serializer(), _row).jsonObject,
        )
      )
    }
    _result_findEnrolmentWithLeavingReason?.leavingReason?.also {
      _row -> 
      add(
        DoorReplicationEntity(tableId = 410,
          orUid = 0,
          entity = json.encodeToJsonElement(LeavingReason.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 ClazzEnrolmentDao.getAllEnrolmentsAtTimeByClazzAndPerson_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_accountPersonUid : Long = request.queryParam("accountPersonUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_time : Long = request.queryParam("time")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _result_getAllEnrolmentsAtTimeByClazzAndPerson = getAllEnrolmentsAtTimeByClazzAndPerson(
    clazzUid = _arg_clazzUid,
    accountPersonUid = _arg_accountPersonUid,
    time = _arg_time,
  )
  val replicationEntities = buildList<DoorReplicationEntity> {
    addAll(
      _result_getAllEnrolmentsAtTimeByClazzAndPerson.map {
        _row ->
        DoorReplicationEntity(tableId = 65,
          orUid = 0,
          entity = json.encodeToJsonElement(ClazzEnrolment.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 ClazzEnrolmentDao.findByClazzUidAndRole_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_roleId : Int = request.queryParam("roleId")?.let {
    json.decodeFromString(Int.serializer(), it)
  } ?: 0
  val _arg_sortOrder : Int = request.queryParam("sortOrder")?.let {
    json.decodeFromString(Int.serializer(), it)
  } ?: 0
  val _arg_searchText : String? = request.queryParam("searchText")?.let {
    json.decodeFromString(String.serializer().nullable, it)
  }
  val _arg_filter : Int = request.queryParam("filter")?.let {
    json.decodeFromString(Int.serializer(), it)
  } ?: 0
  val _arg_accountPersonUid : Long = request.queryParam("accountPersonUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_currentTime : Long = request.queryParam("currentTime")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_permission : Long = request.queryParam("permission")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _pagingLoadParams = request.requirePagingSourceLoadParams(
    json = json,
    keyDeserializationStrategy = Int.serializer().nullable,
  )

  val _result_findByClazzUidAndRole_pagingSource = findByClazzUidAndRole(
    clazzUid = _arg_clazzUid,
    roleId = _arg_roleId,
    sortOrder = _arg_sortOrder,
    searchText = _arg_searchText,
    filter = _arg_filter,
    accountPersonUid = _arg_accountPersonUid,
    currentTime = _arg_currentTime,
    permission = _arg_permission,
  ).loadPageDataForHttp(_pagingLoadParams)
  val _result_findByClazzUidAndRole = _result_findByClazzUidAndRole_pagingSource.data
  serverConfig.logger.log(DoorLogLevel.VERBOSE,
      "DoorPaging: loaded from: ${_pagingLoadParams.key} endOfPaginationReached=${_result_findByClazzUidAndRole_pagingSource.endOfPaginationReached}")
  val _endOfPaginationReached = _result_findByClazzUidAndRole_pagingSource.endOfPaginationReached

  val _result_findEnrolmentsByClazzUidAndRole = findEnrolmentsByClazzUidAndRole(
    clazzUid = _arg_clazzUid,
    accountPersonUid = _arg_accountPersonUid,
    roleId = _arg_roleId,
    permission = _arg_permission,
  )
  val replicationEntities = buildList<DoorReplicationEntity> {
    addAll(
      _result_findByClazzUidAndRole.mapNotNull {
        _row ->
        _row.person?.let {
          DoorReplicationEntity(tableId = 9,
            orUid = 0,
            entity = json.encodeToJsonElement(Person.serializer(), it).jsonObject,
          )
        }

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

      }
    )
    addAll(
      _result_findEnrolmentsByClazzUidAndRole.map {
        _row ->
        DoorReplicationEntity(tableId = 65,
          orUid = 0,
          entity = json.encodeToJsonElement(ClazzEnrolment.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,
      )
    )
  )
}

@Suppress("LocalVariableName", "RedundantSuppression", "FunctionName",
    "RedundantVisibilityModifier")
public suspend
    fun ClazzEnrolmentDao.findByClazzUidAndRoleForGradebook_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_roleId : Int = request.queryParam("roleId")?.let {
    json.decodeFromString(Int.serializer(), it)
  } ?: 0
  val _arg_sortOrder : Int = request.queryParam("sortOrder")?.let {
    json.decodeFromString(Int.serializer(), it)
  } ?: 0
  val _arg_searchText : String? = request.queryParam("searchText")?.let {
    json.decodeFromString(String.serializer().nullable, it)
  }
  val _arg_filter : Int = request.queryParam("filter")?.let {
    json.decodeFromString(Int.serializer(), it)
  } ?: 0
  val _arg_accountPersonUid : Long = request.queryParam("accountPersonUid")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _arg_currentTime : Long = request.queryParam("currentTime")?.let {
    json.decodeFromString(Long.serializer(), it)
  } ?: 0L
  val _pagingLoadParams = request.requirePagingSourceLoadParams(
    json = json,
    keyDeserializationStrategy = Int.serializer().nullable,
  )

  val _result_findByClazzUidAndRoleForGradebook_pagingSource = findByClazzUidAndRoleForGradebook(
    clazzUid = _arg_clazzUid,
    roleId = _arg_roleId,
    sortOrder = _arg_sortOrder,
    searchText = _arg_searchText,
    filter = _arg_filter,
    accountPersonUid = _arg_accountPersonUid,
    currentTime = _arg_currentTime,
  ).loadPageDataForHttp(_pagingLoadParams)
  val _result_findByClazzUidAndRoleForGradebook =
      _result_findByClazzUidAndRoleForGradebook_pagingSource.data
  serverConfig.logger.log(DoorLogLevel.VERBOSE,
      "DoorPaging: loaded from: ${_pagingLoadParams.key} endOfPaginationReached=${_result_findByClazzUidAndRoleForGradebook_pagingSource.endOfPaginationReached}")
  val _endOfPaginationReached =
      _result_findByClazzUidAndRoleForGradebook_pagingSource.endOfPaginationReached

  val _result_findEnrolmentsByClazzUidAndRolePaged = findEnrolmentsByClazzUidAndRolePaged(
    clazzUid = _arg_clazzUid,
    roleId = _arg_roleId,
    sortOrder = _arg_sortOrder,
    searchText = _arg_searchText,
    filter = _arg_filter,
    accountPersonUid = _arg_accountPersonUid,
    currentTime = _arg_currentTime,
    permission = 128,
    studentsLimit = getLimit(_pagingLoadParams, (_pagingLoadParams.key ?: 0)),
    studentsOffset = getOffset(_pagingLoadParams, (_pagingLoadParams.key ?: 0), Int.MAX_VALUE),
  )
  val _result_findStatusForStudentsInClazzStatements =
      request.db.doorWrapper.getDaoByClass(StatementDao::class).findStatusForStudentsInClazzStatements(
    clazzUid = _arg_clazzUid,
    roleId = _arg_roleId,
    sortOrder = _arg_sortOrder,
    searchText = _arg_searchText,
    filter = _arg_filter,
    accountPersonUid = _arg_accountPersonUid,
    currentTime = _arg_currentTime,
    studentsLimit = getLimit(_pagingLoadParams, (_pagingLoadParams.key ?: 0)),
    studentsOffset = getOffset(_pagingLoadParams, (_pagingLoadParams.key ?: 0), Int.MAX_VALUE),
    completionOrProgressTrueVal = true,
  )
  val _result_findActorEntitiesForGradebook = findActorEntitiesForGradebook(
    clazzUid = _arg_clazzUid,
    roleId = _arg_roleId,
    sortOrder = _arg_sortOrder,
    searchText = _arg_searchText,
    filter = _arg_filter,
    accountPersonUid = _arg_accountPersonUid,
    currentTime = _arg_currentTime,
    studentsLimit = getLimit(_pagingLoadParams, (_pagingLoadParams.key ?: 0)),
    studentsOffset = getOffset(_pagingLoadParams, (_pagingLoadParams.key ?: 0), Int.MAX_VALUE),
  )
  val replicationEntities = buildList<DoorReplicationEntity> {
    addAll(
      _result_findByClazzUidAndRoleForGradebook.mapNotNull {
        _row ->
        _row.person?.let {
          DoorReplicationEntity(tableId = 9,
            orUid = 0,
            entity = json.encodeToJsonElement(Person.serializer(), it).jsonObject,
          )
        }

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

      }
    )
    addAll(
      _result_findEnrolmentsByClazzUidAndRolePaged.map {
        _row ->
        DoorReplicationEntity(tableId = 65,
          orUid = 0,
          entity = json.encodeToJsonElement(ClazzEnrolment.serializer(), _row).jsonObject,
        )
      }
    )
    addAll(
      _result_findStatusForStudentsInClazzStatements.mapNotNull {
        _row ->
        _row.statementEntity?.let {
          DoorReplicationEntity(tableId = 60,
            orUid = 0,
            entity = json.encodeToJsonElement(StatementEntity.serializer(), it).jsonObject,
          )
        }

      }
    )
    addAll(
      _result_findStatusForStudentsInClazzStatements.mapNotNull {
        _row ->
        _row.groupMemberActorJoin?.let {
          DoorReplicationEntity(tableId = 4_232,
            orUid = 0,
            entity = json.encodeToJsonElement(GroupMemberActorJoin.serializer(), it).jsonObject,
          )
        }

      }
    )
    addAll(
      _result_findStatusForStudentsInClazzStatements.mapNotNull {
        _row ->
        _row.actorEntity?.let {
          DoorReplicationEntity(tableId = 68,
            orUid = 0,
            entity = json.encodeToJsonElement(ActorEntity.serializer(), it).jsonObject,
          )
        }

      }
    )
    addAll(
      _result_findActorEntitiesForGradebook.map {
        _row ->
        DoorReplicationEntity(tableId = 68,
          orUid = 0,
          entity = json.encodeToJsonElement(ActorEntity.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,
      )
    )
  )
}
