package com.rosetta.messenger.network

/**
 * Message packet (ID: 0x06)
 * Отправка и получение сообщений
 */
class PacketMessage : Packet() {
    var fromPublicKey: String = ""
    var toPublicKey: String = ""
    var content: String = ""            // Зашифрованный текст
    var chachaKey: String = ""          // RSA зашифрованный ключ
    var timestamp: Long = 0
    var privateKey: String = ""         // Hash приватного ключа (для авторизации)
    var messageId: String = ""
    var aesChachaKey: String = ""       // ChaCha key+nonce зашифрованный приватным ключом отправителя
    var attachments: List<MessageAttachment> = emptyList()

    override fun getPacketId(): Int = 0x06

    override fun receive(stream: Stream) {
        fromPublicKey = stream.readString()
        toPublicKey = stream.readString()
        content = stream.readString()
        chachaKey = stream.readString()
        timestamp = stream.readInt64()
        privateKey = stream.readString()
        messageId = stream.readString()

        val attachmentCount = stream.readInt8()
        val attachmentsList = mutableListOf<MessageAttachment>()
        for (i in 0 until attachmentCount) {
            attachmentsList.add(MessageAttachment(
                id = stream.readString(),
                preview = stream.readString(),
                blob = stream.readString(),
                type = AttachmentType.fromInt(stream.readInt8())
            ))
        }
        attachments = attachmentsList
        aesChachaKey = stream.readString()
    }

    override fun send(): Stream {
        val stream = Stream()
        stream.writeInt16(getPacketId())
        stream.writeString(fromPublicKey)
        stream.writeString(toPublicKey)
        stream.writeString(content)
        stream.writeString(chachaKey)
        stream.writeInt64(timestamp)
        stream.writeString(privateKey)
        stream.writeString(messageId)
        stream.writeInt8(attachments.size)

        for (attachment in attachments) {
            stream.writeString(attachment.id)
            stream.writeString(attachment.preview)
            stream.writeString(attachment.blob)
            stream.writeInt8(attachment.type.value)
        }
        stream.writeString(aesChachaKey)

        return stream
    }
}
