/*
 * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
 *
 * Copyright (c) 2015 - 2026 CCBlueX
 *
 * LiquidBounce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * LiquidBounce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
 */
package net.ccbluex.liquidbounce.features.module.modules.exploit.phase.modes

import net.ccbluex.liquidbounce.config.types.group.Mode
import net.ccbluex.liquidbounce.config.types.group.ModeValueGroup
import net.ccbluex.liquidbounce.event.EventState
import net.ccbluex.liquidbounce.event.events.BlinkPacketEvent
import net.ccbluex.liquidbounce.event.events.BlockShapeEvent
import net.ccbluex.liquidbounce.event.events.PacketEvent
import net.ccbluex.liquidbounce.event.events.PlayerNetworkMovementTickEvent
import net.ccbluex.liquidbounce.event.events.PlayerTickEvent
import net.ccbluex.liquidbounce.event.events.TickPacketProcessEvent
import net.ccbluex.liquidbounce.event.events.TransferOrigin
import net.ccbluex.liquidbounce.event.handler
import net.ccbluex.liquidbounce.features.blink.BlinkManager
import net.ccbluex.liquidbounce.features.blink.BlinkManager.Action
import net.ccbluex.liquidbounce.features.module.modules.exploit.phase.ModulePhase
import net.ccbluex.liquidbounce.features.module.modules.exploit.phase.modes.PhaseBlink.boxHandler
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug.debugParameter
import net.ccbluex.liquidbounce.utils.entity.doesCollideAt
import net.ccbluex.liquidbounce.utils.kotlin.EventPriorityConvention
import net.minecraft.network.protocol.game.ClientboundBlockEventPacket
import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket
import net.minecraft.network.protocol.game.ClientboundChunkBatchFinishedPacket
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket
import net.minecraft.network.protocol.game.ClientboundSectionBlocksUpdatePacket
import net.minecraft.network.protocol.game.ClientboundSetTitleTextPacket
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket
import net.minecraft.world.phys.shapes.Shapes

/**
 * Allows you to phase through blocks by blinking until the blocks disappear.
 * For example, before a round start. It will wait until you your collision box collides with a box,
 * then starts to blink until the box disappears.
 *
 * Similar with:
 * [net.ccbluex.liquidbounce.features.module.modules.movement.ModuleFreeze]
 */
object PhaseBlink : Mode("Blink") {

    override val parent: ModeValueGroup<*>
        get() = ModulePhase.mode

    private var maximumTicks by int("Maximum", 120, 1..300, "ticks")

    private var state = State.WAITING
    private var currentTicks = 0

    /**
     * Pauses [boxHandler] when we are checking for collisions
     */
    private var isInCollisionCheck = false

    override fun enable() {
        state = State.WAITING
        currentTicks = 0
        super.enable()
    }

    override fun disable() {
        state = State.FLUSHING
        // This is very important; otherwise the anti-cheat will know that we've
        // started walking through a block before it disappeared
        BlinkManager.flush(TransferOrigin.INCOMING)
        state = State.WAITING
        super.disable()
    }

    @Suppress("unused")
    private val tickPacketHandler = handler<TickPacketProcessEvent> {
        debugParameter("State") { state }

        if (state == State.WALKING) {
            try {
                isInCollisionCheck = true

                // Check if the collisions disappeared
                if (BlinkManager.positions.none { pos -> player.doesCollideAt(pos) }) {
                    ModulePhase.enabled = false
                }
            } finally {
                isInCollisionCheck = false
            }
        }
    }

    @Suppress("unused")
    private val tickHandler = handler<PlayerTickEvent> { event ->
        if (currentTicks > maximumTicks) {
            event.cancelEvent()
        } else if (state == State.PHASING || state == State.WALKING) {
            currentTicks++
        }

        debugParameter("Ticks") { currentTicks }
    }

    /**
     * [PlayerNetworkMovementTickEvent] on [EventState.PRE] lets us have the phased-in position,
     * and start the blinking before sending out the [ServerboundMovePlayerPacket].
     */
    @Suppress("unused")
    private val movementTickHandler = handler<PlayerNetworkMovementTickEvent> { event ->
        if (event.state == EventState.POST) {
            return@handler
        }

        try {
            isInCollisionCheck = true

            if (state == State.WAITING) {
                // Check if we should start phasing
                if (player.doesCollideAt()) {
                    state = State.PHASING
                }
            } else if (state == State.PHASING) {
                if (!player.doesCollideAt()) {
                    state = State.WALKING
                }
            }
        } finally {
            isInCollisionCheck = false
        }
    }

    @Suppress("unused")
    private val boxHandler = handler<BlockShapeEvent> { event ->
        if (isInCollisionCheck || state.boxCollisions) {
            return@handler
        }

        if (event.pos.y >= player.position().y || player.isShiftKeyDown && player.onGround()) {
            event.shape = Shapes.empty()
        }
    }

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

        if (packet is ClientboundPlayerPositionPacket) {
            ModulePhase.enabled = false
        }
    }

    @Suppress("unused")
    private val fakeLagHandler = handler<BlinkPacketEvent>(
        priority = EventPriorityConvention.SAFETY_FEATURE
    ) { event ->
        if (state == State.WAITING) {
            return@handler
        }

        event.action = when (event.packet) {
            is ClientboundBlockUpdatePacket, is ClientboundBlockEventPacket,
            is ClientboundSectionBlocksUpdatePacket, is ClientboundLevelChunkWithLightPacket,
            is ClientboundChunkBatchFinishedPacket, is ClientboundSetTitleTextPacket -> {
                Action.PASS
            }

            else -> if (state == State.PHASING || state == State.WALKING) {
                Action.QUEUE
            } else {
                Action.PASS
            }
        }
    }


    private enum class State(val boxCollisions: Boolean) {
        WAITING(false),
        PHASING(false),
        WALKING(true),
        FLUSHING(true)
    }

}
