package net.moonleay.gimble.networking

import kotlinx.serialization.cbor.Cbor
import kotlinx.serialization.decodeFromByteArray
import kotlinx.serialization.encodeToByteArray
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking
import net.minecraft.network.PacketByteBuf
import net.minecraft.server.network.ServerPlayerEntity
import net.moonleay.gimble.editor.ServerEditorManager
import net.moonleay.gimble.editor.state.EditorState
import net.moonleay.gimble.editor.state.GimblePolicyType
import net.moonleay.gimble.editor.util.GimblePolicy

object GimbleServer {

    fun registerPacketHandler() {
        ServerPlayNetworking
            .registerGlobalReceiver(PacketIDs.UPDATE_EDITOR_STATE_ID)
            { server, player, handler, buf, responseSender ->
                handleStateUpdate(player, buf)
        }
        ServerPlayNetworking
            .registerGlobalReceiver(PacketIDs.GIMBLE_PRERENCE_CHECK_ID)
            { server, player, handler, buf, responseSender ->
                handlePresenceCheck(player, buf)
            }
    }

    private fun handleStateUpdate(player: ServerPlayerEntity, buf: PacketByteBuf){
        val state = Cbor.decodeFromByteArray<EditorState>(buf.readByteArray())
        ServerEditorManager.updateEditorState(player.uuid, state)
//        player.sendMessage(Text.of("Mode: ${state.editorMode} with ${state.editorModifier}"))
    }

    private fun handlePresenceCheck(player: ServerPlayerEntity, buf: PacketByteBuf) {
        val state = Cbor.decodeFromByteArray<EditorState>(buf.readByteArray())
        ServerEditorManager.updateEditorState(player.uuid, state)

        val buffer = PacketByteBufs.create()
        buffer.writeByteArray(Cbor.encodeToByteArray(GimblePolicy(GimblePolicyType.ALLOWED)))
        ServerPlayNetworking.send(player, PacketIDs.TRANSFER_GIMBLE_POLICY_ID, buffer)
    }
}
