import { world } from "@minecraft/server";
import { replaySessions } from "../../data/replay-player-session";
import config from "../../data/util/config";
import { debugLog } from "../../data/util/debug";
function captureCompleteData(eventData) {
    const player = eventData.source;
    const session = replaySessions.playerSessions.get(player.id);
    if (!session || session.replayStateMachine.state !== "recPending")
        return;
    const bowEvents = session.playerItemUseDataMap.get(player.id);
    if (!bowEvents?.length)
        return;
    const tick = session.recordingEndTick;
    const lastEvent = bowEvents[bowEvents.length - 1];
    const excludedTypes = ["minecraft:bow", "minecraft:crossbow", "minecraft:trident"];
    // Special handling for crossbows
    if (lastEvent.typeId === "minecraft:crossbow") {
        debugLog("Crossbow After Event");
        if (lastEvent.endTime === 0) {
            // First release = charged but not fired
            lastEvent.endTime = tick;
            lastEvent.chargeTime = lastEvent.endTime - lastEvent.startTime;
            lastEvent.isCharged = true;
            debugLog(`[ReplayCraft DEBUG] Crossbow charged: ${JSON.stringify(lastEvent)}`);
            if (config.debugItemUseEvents === true) {
                debugLog(`[ReplayCraft DEBUG] Crossbow charged: ${JSON.stringify(lastEvent)}`);
            }
        }
        else if (lastEvent.isCharged && !lastEvent.firedAt) {
            // Second release = fire the charged projectile
            lastEvent.firedAt = tick;
            lastEvent.isCharged = false; // consumed
            if (config.debugItemUseEvents === true) {
                debugLog(`[ReplayCraft DEBUG] Crossbow fired: ${JSON.stringify(lastEvent)}`);
            }
        }
    }
    //Handle other items
    if (!excludedTypes.includes(eventData.itemStack.typeId)) {
        if (lastEvent.endTime === 0) {
            lastEvent.endTime = tick;
            lastEvent.chargeTime = lastEvent.endTime - lastEvent.startTime;
            if (config.debugItemUseEvents) {
                debugLog(`[ReplayCraft DEBUG] Item completed: ${eventData.itemStack.typeId} at tick ${tick}`);
            }
        }
    }
}
const replayCraftItemCompleteUseAfterEvent = () => {
    world.afterEvents.itemCompleteUse.subscribe(captureCompleteData);
};
export { replayCraftItemCompleteUseAfterEvent };
