package ru.dbotthepony.kstarbound.server

import org.apache.logging.log4j.LogManager
import ru.dbotthepony.kstarbound.defs.ChatMessage
import ru.dbotthepony.kstarbound.defs.ChatSendMode
import ru.dbotthepony.kstarbound.defs.MessageContext
import ru.dbotthepony.kstarbound.network.packets.clientbound.ChatReceivePacket
import ru.dbotthepony.kstarbound.network.packets.serverbound.ChatSendPacket

class ChatHandler(val server: StarboundServer) {
	fun systemMessage(string: String) {
		LOGGER.info("Chat: <Server> {}", string)

		server.channels.broadcast(ChatReceivePacket(
			ChatMessage(
				MessageContext.BROADCAST,
				text = string
			)
		))
	}

	fun handle(source: ServerConnection, packet: ChatSendPacket) {
		when (packet.mode) {
			ChatSendMode.BROADCAST -> {
				LOGGER.info("Chat: <{}> {}", source.nickname, packet.text)
				server.channels.broadcast(ChatReceivePacket(ChatMessage(MessageContext.BROADCAST, sender = source.connectionID, senderNick = source.nickname, text = packet.text)))
			}

			ChatSendMode.LOCAL -> {
				val world = source.world

				if (world == null) {
					LOGGER.warn("{} tried to say something, but they are in limbo: {}", source.nickname, packet.text)

					source.send(ChatReceivePacket(
						ChatMessage(
							MessageContext.COMMAND_RESULT,
							text = "You appear to be in limbo, nobody can hear you! Use Global chat."
						)
					))
				} else {
					LOGGER.info("Local chat: <{}> {}", source.nickname, packet.text)

					world.broadcast(ChatReceivePacket(
						ChatMessage(
							MessageContext.LOCAL,
							sender = source.connectionID,
							senderNick = source.nickname,
							text = packet.text
						)
					))
				}
			}

			ChatSendMode.PARTY -> {
				source.send(ChatReceivePacket(
					ChatMessage(
						MessageContext.COMMAND_RESULT,
						text = "Party chat not implemented."
					)
				))
			}
		}
	}

	companion object {
		private val LOGGER = LogManager.getLogger()
	}
}
