import { EntityComponentTypes, ItemLockMode, ItemStack, StructureAnimationMode, StructureRotation, system, world } from "@minecraft/server";
import { createVector, sendDebugMessage, vectorAdd, vectorRoundDown, vectorSubtract } from "./JM_Utils";

system.runInterval(() => {
    world.getAllPlayers().forEach(player => {
        player.dimension.getEntities({type:"lb_as:floating_heart", location: player.location, maxDistance: 1.5, propertyOptions: [{propertyId: "lb_as:allow_pickup", value: true}]}).forEach(entity => {
            const inventory = player.getComponent(EntityComponentTypes.Inventory).container
            const slot = inventory.firstEmptySlot()
            if (slot === undefined) return
            try {
                generateBridge(vectorRoundDown(entity.location), entity.dimension)
            } catch (error) {
                sendDebugMessage(error)
                entity.remove()
                return
            }

            const item = new ItemStack("lb_as:gilded_blackstone_heart",1)
            inventory.addItem(item)
            player.playSound("random.pop")
            entity.remove()
        })
    })
})

const bridgeBuildSeconds = 5

function generateBridge(heartLocation, dimension) {
    dimension.playSound("castle_appears", heartLocation)
    const origin = vectorSubtract(heartLocation, createVector(0, 1, 1))
    const bridgeOrigin = vectorSubtract(origin, createVector(0, 0, 32))
    world.structureManager.place("lb_as:bridge_3", dimension, bridgeOrigin, {animationMode: StructureAnimationMode.Blocks, animationSeconds: bridgeBuildSeconds, rotation: StructureRotation.Rotate180})
    system.runTimeout(() => {
        world.structureManager.place("lb_as:bridge_4", dimension, vectorAdd(bridgeOrigin, createVector(1, 0, 0)), {animationMode: StructureAnimationMode.Blocks, animationSeconds: bridgeBuildSeconds, rotation: StructureRotation.Rotate180})
        world.structureManager.place("lb_as:bridge_2", dimension, vectorSubtract(bridgeOrigin, createVector(1, 0, 0)), {animationMode: StructureAnimationMode.Blocks, animationSeconds: bridgeBuildSeconds, rotation: StructureRotation.Rotate180})
        system.runTimeout(() => {
            world.structureManager.place("lb_as:bridge_5", dimension, vectorAdd(bridgeOrigin, createVector(2, 0, 0)), {animationMode: StructureAnimationMode.Blocks, animationSeconds: bridgeBuildSeconds, rotation: StructureRotation.Rotate180})
            world.structureManager.place("lb_as:bridge_1", dimension, vectorSubtract(bridgeOrigin, createVector(2, 0, 0)), {animationMode: StructureAnimationMode.Blocks, animationSeconds: bridgeBuildSeconds, rotation: StructureRotation.Rotate180})
        },1)
    },1)
    const castleOrigin = vectorSubtract(bridgeOrigin, createVector(19, 10, 43))
    world.structureManager.place("lb_as:castle_boss", dimension, castleOrigin, {animationMode: StructureAnimationMode.Layers, animationSeconds: bridgeBuildSeconds + 3})
}