import { world, BlockPermutation, Dimension, Block, system, ItemStack } from "@minecraft/server";
import { age1_quests_en } from "./languages.js"
import { itemDurability, itemAttack, itemMine } from './itemDurability'
import { decrementstack } from './bum_crops_custom_components.js'


var gloomylist = ["minecraft:moss_block", "mb:gloomy_stone", "minecraft:grass"]
var netherlist = ["minecraft:netherrack", "minecraft:crimson_nylium", "minecraft:warped_nylium"]
var gloomyfoliage = ["mb:gloomy_sprouts", "mb:gloomy_grass", "mb:gloomy_grass"]
var netherfoliage = ["minecraft:warped_roots", "minecraft:crimson_roots", "minecraft:nether_sprouts"]
var gloomywood = ["mb:gloomy_stone_pillar", "mb:gloomy_stone_pillar"]
var netherwood = ["minecraft:crimson_stem", "minecraft:warped_stem"]
var gloomyshroom = ["pcr:mb_gloomyshroom"]
var nethershroom = ["minecraft:crimson_fungus"]
var gloomysand = ["mb:light_skulk", "minecraft:sculk", "mb:light_skulk"]
var nethersand = ["minecraft:soul_sand", "minecraft:magma", "minecraft:netherrack"]
var gloomysnow = ["rns:frostedmud", "rns:permafrost", "rns:frostedmud"]
var nethersnow = ["minecraft:soul_soil", "rns:permafrost", "minecraft:soul_sand"]
var gloomycoal = ["mb:chartrium_ore", "mb:chartrium_ore", "mb:chartrium_ore"]
var nethercoal = ["minecraft:nether_gold_ore", "minecraft:nether_gold_ore", "minecraft:nether_gold_ore"]

let growth = 0
let message = 0
let bedmessage = 0

//Set Up Scoreboard
world.afterEvents.playerSpawn.subscribe((eventData) => {
    const source = eventData.player
    const firstspawn = eventData.initialSpawn
    if (firstspawn && !source.hasTag("pcr:hasjoined")) {
        source.runCommandAsync('scoreboard objectives add quests dummy')
        source.runCommandAsync('scoreboard objectives add questfin dummy')
        source.runCommandAsync('scoreboard objectives add quest1 dummy')
        source.runCommandAsync('scoreboard objectives add quest2 dummy')
        source.runCommandAsync('scoreboard objectives add quest3 dummy')
        source.runCommandAsync('scoreboard objectives add language dummy')
        source.runCommandAsync('scoreboard players add @s quests 0')
        source.runCommandAsync('scoreboard players add @s questfin 1')
        source.runCommandAsync('scoreboard players add @s quest1 0')
        source.runCommandAsync('scoreboard players add @s quest2 0')
        source.runCommandAsync('scoreboard players add @s quest3 0')
        source.runCommandAsync('scoreboard players add @s language 0')
        //Intro Stuff
        source.getComponent('inventory').container.setItem(0, new ItemStack('pcr:questbook', 1))
        source.addTag("pcr:hasjoined")
    }

})


world.beforeEvents.playerBreakBlock.subscribe((eventData) => {
    const block = eventData.block
    const item = eventData.itemStack
    const player = eventData.player
    const inv = player.getComponent("minecraft:inventory").container
    const slot = player.selectedSlotIndex
    const blockname = eventData.block.typeId
    //Mining Durability
    if (item?.hasTag("pcr:itemMine")) {
        system.run(() => {
            itemMine(player)
        })

    }
})

world.beforeEvents.playerInteractWithBlock.subscribe((eventData) => {
    var block = eventData.block
    var player = eventData.player

    if (block.typeId == "minecraft:crafting_table") {
        eventData.cancel = true
    }
    if (block.typeId == "minecraft:anvil") {
        eventData.cancel = true
    }
    if (block.typeId == "minecraft:bed") {
        player.runCommandAsync('scoreboard objectives add beds dummy')
        player.runCommandAsync('scoreboard players add @s beds 0')
        if (world.scoreboard.getObjective('beds').getScore(player) < 1) {
            eventData.cancel = true
            bedmessage = bedmessage + 1
            if (bedmessage % 4 == 0) {
                player.sendMessage("Unlock Beds after the sleeping ritual")
                bedmessage = 1
            }

        }
    }
    if (block.typeId == "minecraft:furnace") {
        if (world.scoreboard.getObjective('quests').getScore(player) < 27) {
            eventData.cancel = true
            message = message + 1
            if (message % 4 == 0) {
                player.sendMessage("Unlock Furnace Functions after Quest " + age1_quests_en[17])
                message = 1
            }

        }
    }

})

world.beforeEvents.itemUseOn.subscribe((eventData) => {
    var block = eventData.block
    var player = eventData.source
    var item = eventData.itemStack
    var firsttime = eventData.isFirstEvent
    var blockface = eventData.blockFace


    if (firsttime == true) {
        if (item?.typeId == "rns:pebble" && player.isSneaking) {
            if (block?.hasTag("stone") && blockface != "up") {
                eventData.cancel = true
                system.run(() => {
                    block.dimension.playSound('use.stone', block.center())
                    decrementstack(item, player, item.typeId)
                    const newItem2 = block.dimension.spawnItem(new ItemStack('hax:stone_pebble'), block.center());
                    const direction = getDirection(newItem2.location, player.location);
                    const power = 2;
                    newItem2.applyImpulse({ x: direction.x * power, y: direction.y * power, z: direction.z * power });
                })
            }
        }
        if (item?.typeId == "minecraft:stick" && player.isSneaking) {
            if (block?.hasTag("stone")) {
                eventData.cancel = true
                system.run(() => {
                    block.dimension.playSound('use.stone', block.center())
                    decrementstack(item, player, item.typeId)
                    const newItem2 = block.dimension.spawnItem(new ItemStack('hax:wooden_shavings', 2), block.center());
                    const direction = getDirection(newItem2.location, player.location);
                    const power = 2;
                    newItem2.applyImpulse({ x: direction.x * power, y: direction.y * power, z: direction.z * power });
                })
            }
        }
    }

})




function finQuest(player, block) {
    player.runCommandAsync('scoreboard players add @p quests 1')
    player.runCommandAsync('playsound random.orb @p ' + + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z))
}

function finQuest1(player, block) {
    player.runCommandAsync('scoreboard players add @p quest1 1')
    player.runCommandAsync('playsound random.orb @p ' + + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z))
}

function finQuest2(player, block) {
    player.runCommandAsync('scoreboard players add @p quest2 1')
    player.runCommandAsync('playsound random.orb @p ' + + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z))
}

function finQuest3(player, block) {
    player.runCommandAsync('scoreboard players add @p quest3 1')
    player.runCommandAsync('playsound random.orb @p ' + + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z))
}


//Ashen Rotation Logic
world.afterEvents.playerPlaceBlock.subscribe((eventData) => {
    const { block, player } = eventData;
    if (block?.typeId == "pcr:ashenbrick" || block?.typeId == "pcr:forgeheater" || block?.typeId == "pcr:forgemelter") {
        if (block.location.x % 2 == 0) {
            block.setPermutation(block.permutation.withState('pcr:brickstylex', 1))
        }
        if (block.location.z % 2 == 0) {
            block.setPermutation(block.permutation.withState('pcr:brickstylez', 1))
        }
    }
})

world.beforeEvents.playerInteractWithBlock.subscribe((eventData) => {
    const item = eventData.itemStack
    const user = eventData.player
    const block = eventData.block
    const inv = user.getComponent("minecraft:inventory").container
    const player = eventData.player
    const slot = player.selectedSlotIndex

    const quests = world.scoreboard.getObjective('quests').getScore(user)
    const quest1 = world.scoreboard.getObjective('quest1').getScore(user)
    const quest2 = world.scoreboard.getObjective('quest2').getScore(user)
    const quest3 = world.scoreboard.getObjective('quest3').getScore(user)
    if (getTimeSinceLastClick(user) < 100) return;

    //Progression Specific
    if (block.typeId == "pcr:offeringbox") {
        if (!user.isSneaking) {
            eventData.cancel = true
        }

        //Quests 
        system.runTimeout(() => {
            if (quests == 1 && item?.typeId == "minecraft:cactus" || quests == 1 && item?.hasTag('pcr:petal')) {
                finQuest(user, block)

            }
            else if (quests == 4 && item?.typeId == "sev:choppingblock") {
                finQuest(user, block)

            }
            else if (quests == 7 && item?.hasTag("minecraft:planks")) {
                finQuest(user, block)

            }
            else if (quests == 10 && item?.typeId == "sev:makeshifttable") {
                finQuest(user, block)

            }
            else if (quests == 13 && item?.typeId == "pcr:woodencrucible") {
                finQuest(user, block)

            }
            else if (quests == 16 && item?.typeId == "btb:makeshiftsieve") {
                finQuest(user, block)

            }
            else if (quests == 19 && item?.typeId == "sev:advmakeshifttable") {
                finQuest(user, block)

            }
            else if (quests == 22 && item?.typeId == "minecraft:wooden_pickaxe") {
                finQuest(user, block)

            }
            else if (quests == 25 && item?.typeId == "minecraft:furnace") {
                finQuest(user, block)

            }
            else if (quests == 28 && item?.typeId == "pcr:claycooker") {
                finQuest(user, block)

            }
            else if (quests == 31 && item?.typeId == "bumble:mug") {
                finQuest(user, block)

            }
            else if (quests == 34 && item?.typeId == "pcr:claybasin") {
                finQuest(user, block)

            }
            else if (quests == 37 && item?.typeId == "pcr:claysteamer") {
                finQuest(user, block)

            }
            else if (quests == 40 && item?.typeId == "pcr:porcelainthatchbricks") {
                finQuest(user, block)

            }
            else if (quests == 43 && item?.typeId == "sev:primaltable") {
                finQuest(user, block)
            }
            else if (quests == 46 && item?.typeId == "minecraft:brush") {
                finQuest(user, block)
            }
            else if (quests == 49 && item?.typeId == "pcr:carvedboneblock") {
                finQuest(user, block)
            }
            else if (quests == 52 && item?.typeId == "minecraft:fermented_spider_eye") {
                finQuest(user, block)
            }
            else if (quests == 55 && item?.typeId == "mb:mossy_bony_pickaxe") {
                finQuest(user, block)
            }
            else if (quests == 58 && item?.typeId == "sev:woodupgprimaltable") {
                finQuest(user, block)
            }
            else if (quests == 61 && item?.typeId == "vatonage:cogwheel") {
                finQuest(user, block)
            }
            else if (quests == 64 && item?.typeId == "vatonage:crushing_wheel") {
                finQuest(user, block)
            }
            else if (quests == 67 && item?.hasTag('pcr:rune')) {
                finQuest(user, block)
            }
            else if (quests == 70 && item?.typeId == "pcr:nethersummon") {
                finQuest(user, block)
            }
            else if (quests == 73 && item?.typeId == "rns:warpedbark") {
                finQuest(user, block)
            }
            else if (quests == 76 && item?.typeId == "pcr:cursedblazespawnegg") {
                finQuest(user, block)
            }
            else if (quests == 79 && item?.typeId == "pcr:flame") {
                finQuest(user, block)
            }
            else if (quests == 82 && item?.typeId == "pcr:ashenbrick") {
                finQuest(user, block)
            }
            else if (quests == 85 && item?.typeId == "pcr:forgeheater") {
                finQuest(user, block)
            }
            else if (quests == 88 && item?.typeId == "pcr:forgemelter") {
                finQuest(user, block)
            }
            else if (quests == 91 && item?.typeId == "pcr:smeltableprimalbronzeblend") {
                finQuest(user, block)
            }
            else if (quests == 94 && item?.typeId == "pcr:bronzepickaxe") {
                finQuest(user, block)
            }
            else if (quests == 97 && item?.typeId == "pcr:irontable") {
                finQuest(user, block)
            }

            //Splitquests 1
            else if (quest1 == 1 && item?.typeId == "mms:campfirebase") {
                finQuest1(user, block)

            }
            else if (quest1 == 4 && item?.typeId == "sev:fireflint") {
                finQuest1(user, block)

            }
            else if (quest1 == 7 && item?.hasTag('pcr:food_charcoal')) {
                finQuest1(user, block)

            }
            else if (quest1 == 10 && item?.typeId == "minecraft:charcoal") {
                finQuest1(user, block)
            }
            //
            else if (quest1 == 13 && item?.typeId == "rns:flintscraper") {
                finQuest1(user, block)

            }
            else if (quest1 == 16 && item?.typeId == "sev:flintaxe") {
                finQuest1(user, block)

            }
            else if (quest1 == 19 && item?.typeId == "sev:flint_broadsword") {
                finQuest1(user, block)

            }
            else if (quest1 == 22 && item?.typeId == "add:scraped_hide") {
                finQuest1(user, block)

            }
            else if (quest1 == 25 && item?.typeId == "add:tanned_hide") {
                finQuest1(user, block)

            }
            else if (quest1 == 28 && item?.typeId == "minecraft:leather") {
                finQuest1(user, block)

            }
            else if (quest1 == 31 && item?.typeId == "rns:andesitemortar") {
                finQuest1(user, block)

            }
            else if (quest1 == 34 && item?.typeId == "rns:pinksalt") {
                finQuest1(user, block)

            }
            else if (quest1 == 37 && item?.typeId == "minecraft:purple_dye") {
                finQuest1(user, block)

            }
            else if (quest1 == 40 && item?.typeId == "minecraft:amethyst_shard") {
                finQuest1(user, block)

            }
            else if (quest1 == 43 && item?.typeId == "pcr:porcelainclay") {
                finQuest1(user, block)

            }
            else if (quest1 == 46 && item?.typeId == "pcr:porcelainbricks") {
                finQuest1(user, block)
            }
            else if (quest1 == 49 && item?.typeId == "minecraft:moss_block") {
                finQuest1(user, block)
            }
            else if (quest1 == 52 && item?.typeId == "pcr:gloomyshroom") {
                finQuest1(user, block)
            }
            else if (quest1 == 55 && item?.typeId == "mb:chartrium_crystal") {
                finQuest1(user, block)
            }
            else if (quest1 == 58 && item?.typeId == "pcr:tinalloy") {
                finQuest1(user, block)
            }
            else if (quest1 == 61 && item?.typeId == "minecraft:chest") {
                finQuest1(user, block)
            }
            else if (quest1 == 64 && item?.typeId == "hax:copper_greatsword") {
                finQuest1(user, block)
            }
            else if (quest1 == 67 && item?.typeId == "hax:tin_lance") {
                finQuest1(user, block)
            }
            else if (quest1 == 70 && item?.typeId == "minecraft:bow") {
                finQuest1(user, block)
            }

            //Splitquest 2
            else if (quest2 == 1 && item?.typeId == "rns:dryingrack") {
                finQuest2(user, block)

            }
            else if (quest2 == 4 && item?.typeId == "sev:driedcattailreeds") {
                finQuest2(user, block)

            }
            else if (quest2 == 7 && item?.typeId == "minecraft:dried_kelp") {
                finQuest2(user, block)

            }
            else if (quest2 == 10 && (item?.typeId == "minecraft:sugar_cane" || item?.typeId == "rns:rotala_roots")) {
                finQuest2(user, block)

            }
            else if (quest2 == 13 && item?.typeId == "minecraft:paper") {
                finQuest2(user, block)

            }
            else if (quest2 == 16 && item?.typeId == "minecraft:writable_book") {
                finQuest2(user, block)

            }
            else if (quest2 == 19 && item?.typeId == "rns:paperlantern") {
                finQuest2(user, block)

            }
            else if (quest2 == 22 && item?.typeId == "hax:wood_broadsword") {
                finQuest2(user, block)

            }
            else if (quest2 == 25 && item?.typeId == "rns:dryingrackupgrade") {
                finQuest2(user, block)

            }
            else if (quest2 == 28 && item?.typeId == "bps:backpack") {
                finQuest2(user, block)

            }
            else if (quest2 == 31 && item?.typeId == "pcr:respawnnest") {
                finQuest2(user, block)

            }
            else if (quest2 == 34 && item?.typeId == "pcr:packedmudframe") {
                finQuest2(user, block)

            }
            else if (quest2 == 37 && item?.typeId == "minecraft:brick") {
                finQuest2(user, block)
            }
            else if (quest2 == 40 && item?.typeId == "mb:gloomy_stone_bricks") {
                finQuest2(user, block)
            }
            else if (quest2 == 43 && item?.typeId == "pcr:mossclump") {
                finQuest2(user, block)
            }
            else if (quest2 == 46 && item?.typeId == "pcr:mossyscraper") {
                finQuest2(user, block)
            }
            else if (quest2 == 49 && item?.typeId == "minecraft:raw_copper") {
                finQuest2(user, block)
            }
            else if (quest2 == 52 && item?.typeId == "hax:raw_tin") {
                finQuest2(user, block)
            }
            else if (quest2 == 55 && item?.typeId == "sev:twine") {
                finQuest2(user, block)
            }
            else if (quest2 == 58 && item?.typeId == "pcr:ash") {
                finQuest2(user, block)
            }
            else if (quest2 == 61 && item?.typeId == "pcr:dust") {
                finQuest2(user, block)
            }
            else if (quest2 == 64 && item?.typeId == "minecraft:copper_ingot") {
                finQuest2(user, block)
            }
            else if (quest2 == 67 && item?.typeId == "hax:tin_ingot") {
                finQuest2(user, block)
            }



            //Splitquest 3
            else if (quest3 == 1 && item?.typeId == "minecraft:farmland") {
                finQuest3(user, block)

            }
            else if (quest3 == 4 && item?.typeId == "minecraft:wheat") {
                finQuest3(user, block)

            }
            else if (quest3 == 7 && item?.typeId == "sev:thatch") {
                finQuest3(user, block)

            }
            else if (quest3 == 10 && item?.typeId == "sev:fluidbladder") {
                finQuest3(user, block)

            }
            else if (quest3 == 13 && item?.typeId == "sev:fullfluidbladder") {
                finQuest3(user, block)

            }
            else if (quest3 == 16 && item?.typeId == "minecraft:andesite") {
                finQuest3(user, block)

            }
            else if (quest3 == 19 && item?.typeId == "minecraft:cobbled_deepslate") {
                finQuest3(user, block)

            }
            else if (quest3 == 22 && item?.typeId == "minecraft:tuff") {
                finQuest3(user, block)

            }
            else if (quest3 == 25 && item?.typeId == "minecraft:magma") {
                finQuest3(user, block)

            }
            else if (quest3 == 28 && item?.typeId == "pcr:rope") {
                finQuest3(user, block)

            }
            else if (quest3 == 31 && item?.typeId == "vatonage:mechanical_crank") {
                finQuest3(user, block)

            }
            else if (quest3 == 34 && item?.typeId == "pcr:turntable") {
                finQuest3(user, block)
            }
            else if (quest3 == 37 && item?.typeId == "pcr:quartzpress") {
                finQuest3(user, block)
            }
            else if (quest3 == 40 && (item?.typeId == "minecraft:pale_oak_log" || item?.typeId == "minecraft:pale_moss_block")) {
                finQuest3(user, block)
            }
            else if (quest3 == 43 && item?.typeId == "minecraft:resin_clump") {
                finQuest3(user, block)
            }
            else if (quest3 == 46 && item?.typeId == "minecraft:creaking_heart") {
                finQuest3(user, block)
            }
            else if (quest3 == 49 && item?.typeId == "pcr:altarcenter") {
                finQuest3(user, block)
            }
            else if (quest3 == 52 && item?.typeId == "pcr:pedestal") {
                finQuest3(user, block)
            }
            else if (quest3 == 55 && item?.typeId == "minecraft:bed") {
                finQuest3(user, block)
            }
            else if (quest3 == 58 && item?.typeId == "pcr:essenceofsheep") {
                finQuest3(user, block)
            }
            else if (quest3 == 61 && item?.typeId == "minecraft:honey_bottle") {
                finQuest3(user, block)
            }
            else if (quest3 == 64 && item?.typeId == "minecraft:honeycomb") {
                finQuest3(user, block)
            }
            else if (quest3 == 67 && item?.typeId == "minecraft:raw_iron") {
                finQuest3(user, block)
            }
            else if (quest3 == 70 && item?.typeId == "minecraft:iron_ingot") {
                finQuest3(user, block)
            }
        })
    }
    //Altarcenter and Pedestal Specifics
    if (block.typeId == "pcr:altarcenter") {
        if (block.permutation.getState('pcr:active') == 0 && block.permutation.getState('pcr:enchant') == 0 && block.permutation.getState('pcr:ismossy') == 0) {
            if (item?.typeId == "pcr:mossclump") {
                system.run(() => {
                    block.setPermutation(block.permutation.withState('pcr:ismossy', 1))
                    decrementstack(item, user, inv, "pcr:mossclump")
                    user.runCommandAsync('playsound use.moss @p ~ ~ ~')
                })
            }
        }
        if (block.permutation.getState('pcr:active') == 1) {
            //Transformations
            if (item?.typeId == "minecraft:fermented_spider_eye") {
                random_fill(eventData, user, gloomylist, gloomyfoliage, gloomywood, gloomyshroom, gloomysand, gloomysnow, gloomycoal)
                system.run(() => {
                    block.setPermutation(block.permutation.withState('pcr:active', 0))
                    decrementstack(item, user, inv, "minecraft:fermented_spider_eye")
                })
            }
            else if (item?.typeId == "pcr:nethersummon") {
                random_fill(eventData, user, netherlist, netherfoliage, netherwood, nethershroom, nethersand, nethersnow, nethercoal)
                system.run(() => {
                    block.setPermutation(block.permutation.withState('pcr:active', 0))
                    decrementstack(item, user, inv, "pcr:nethersummon")
                })
            }
            //Objectives QOL
            else if (item?.typeId == "pcr:essenceofsheep") {
                user.runCommandAsync('scoreboard players set @s beds 1')
                user.runCommandAsync('playsound random.levelup @p ~ ~ ~')
                player.sendMessage("You can sleep now!")
                system.run(() => {
                    block.setPermutation(block.permutation.withState('pcr:active', 0))
                    decrementstack(item, user, inv, "pcr:essenceofsheep")
                })
            }
            //Enchants
            else if (item?.typeId == "pcr:runeofunbreaking") {
                system.run(() => {
                    block.setPermutation(block.permutation.withState('pcr:active', 0))
                    block.setPermutation(block.permutation.withState('pcr:enchant', 1))
                    decrementstack(item, user, inv, "pcr:runeofunbreaking")
                    user.runCommandAsync('playsound lodestone_compass.link_compass_to_lodestone @p ~ ~ ~')
                })
            }
            else if (item?.typeId == "pcr:runeofefficiency") {
                system.run(() => {
                    block.setPermutation(block.permutation.withState('pcr:active', 0))
                    block.setPermutation(block.permutation.withState('pcr:enchant', 2))
                    decrementstack(item, user, inv, "pcr:runeofefficiency")
                    user.runCommandAsync('playsound lodestone_compass.link_compass_to_lodestone @p ~ ~ ~')
                })
            }
            else if (item?.typeId == "pcr:runeofprotection") {
                system.run(() => {
                    block.setPermutation(block.permutation.withState('pcr:active', 0))
                    block.setPermutation(block.permutation.withState('pcr:enchant', 3))
                    decrementstack(item, user, inv, "pcr:runeofprotection")
                    user.runCommandAsync('playsound lodestone_compass.link_compass_to_lodestone @p ~ ~ ~')
                })
            }
        }
        if (item?.typeId != "pcr:mossclump") {
            if (block.permutation.getState('pcr:enchant') == 3) {
                if (item?.getComponent("minecraft:armor")?.isValid()) {
                    user.runCommandAsync('enchant @s protection')
                    user.runCommandAsync('playsound block.enchanting_table.use @p ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z))
                    system.run(() => {
                        block.setPermutation(block.permutation.withState('pcr:enchant', 0))
                    })
                }
                else {
                    player.sendMessage("Item does not support Protection")
                }
            }

            if (block.permutation.getState('pcr:enchant') == 2) {
                if (item?.hasTag('minecraft:is_axe') || item?.hasTag('minecraft:is_pickaxe') || item?.hasTag('minecraft:is_hoe') || item?.hasTag('minecraft:is_shovel') || item?.typeId.includes("shears")) {
                    user.runCommandAsync('enchant @s efficiency')
                    user.runCommandAsync('playsound block.enchanting_table.use @p ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z))
                    system.run(() => {
                        block.setPermutation(block.permutation.withState('pcr:enchant', 0))
                    })
                }
                else {
                    player.sendMessage("Item does not support Efficiency")
                }
            }

            if (block.permutation.getState('pcr:enchant') == 1) {
                if (item?.getComponent("minecraft:enchantable")?.isValid()) {
                    user.runCommandAsync('enchant @s unbreaking')
                    user.runCommandAsync('playsound block.enchanting_table.use @p ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z))
                    system.run(() => {
                        block.setPermutation(block.permutation.withState('pcr:enchant', 0))
                    })
                }
                else {
                    player.sendMessage("Item does not support Unbreaking")
                }
            }
        }
    }
    //Respawn Nest
    if (item?.typeId == "pcr:respawnnest" && player.isSneaking) {
        user.runCommandAsync('spawnpoint @s' + ' ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z))
        system.run(() => {
            decrementstack(item, user, inv, "pcr:respawnnest")
            player.sendMessage("Spawn Set!")
        })
    }
    if (block.typeId == "pcr:forgemelter") {
        if (block.permutation.getState('pcr:active') == 1) {
            if (item?.typeId == "pcr:smeltablecopper") {
                system.run(() => {
                    decrementstack(item, user, inv, "pcr:smeltablecopper")
                    block.dimension.playSound('use.stone', block.center())
                    decrementstack(item, player, item.typeId)
                    const newItem2 = block.dimension.spawnItem(new ItemStack('minecraft:copper_ingot'), block.center());
                    const direction = getDirection(newItem2.location, player.location);
                    const power = 2;
                    newItem2.applyImpulse({ x: direction.x * power, y: direction.y * power, z: direction.z * power });
                })
            }
            if (item?.typeId == "pcr:smeltabletin") {
                system.run(() => {
                    decrementstack(item, user, inv, "pcr:smeltabletin")
                    block.dimension.playSound('use.stone', block.center())
                    decrementstack(item, player, item.typeId)
                    const newItem2 = block.dimension.spawnItem(new ItemStack('hax:tin_ingot'), block.center());
                    const direction = getDirection(newItem2.location, player.location);
                    const power = 2;
                    newItem2.applyImpulse({ x: direction.x * power, y: direction.y * power, z: direction.z * power });
                })
            }
            if (item?.typeId == "pcr:smeltableprimalbronzeblend") {
                system.run(() => {
                    decrementstack(item, user, inv, "pcr:smeltableprimalbronzeblend")
                    block.dimension.playSound('use.stone', block.center())
                    decrementstack(item, player, item.typeId)
                    const newItem2 = block.dimension.spawnItem(new ItemStack('hax:bronze_ingot'), block.center());
                    const direction = getDirection(newItem2.location, player.location);
                    const power = 2;
                    newItem2.applyImpulse({ x: direction.x * power, y: direction.y * power, z: direction.z * power });
                })
            }
            if (item?.typeId == "pcr:smeltableiron") {
                system.run(() => {
                    decrementstack(item, user, inv, "pcr:smeltableiron")
                    block.dimension.playSound('use.stone', block.center())
                    decrementstack(item, player, item.typeId)
                    const newItem2 = block.dimension.spawnItem(new ItemStack('minecraft:iron_ingot'), block.center());
                    const direction = getDirection(newItem2.location, player.location);
                    const power = 2;
                    newItem2.applyImpulse({ x: direction.x * power, y: direction.y * power, z: direction.z * power });
                })
            }
        }
    }
    //Flint Scraper Functions
    if (item?.typeId == "rns:flintscraper") {
        if (block.typeId == "minecraft:bee_nest" && block.permutation.getState('honey_level') == 5 || block.typeId == "minecraft:beehive" && block.permutation.getState('honey_level') == 5) {
            system.run(() => {
                block.setPermutation(block.permutation.withState('honey_level', 0))
            })
            user.runCommandAsync('loot spawn ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z) + ' loot honeycomb')
            user.runCommandAsync('playsound block.beehive.shear @p ~ ~ ~')
        }
        if (block.typeId == "minecraft:bone_block") {
            user.runCommandAsync('fill ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z) + ' ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z) + ' pcr:carvedboneblock replace' + ' minecraft:bone_block')
            user.runCommandAsync('playsound dig.bone_block @p ~ ~ ~')
        }
    }
    if (block.typeId == "pcr:pedestal") {
        if (block.permutation.getState('pcr:ismossy') == 0) {
            if (item?.typeId == "pcr:mossclump") {
                system.run(() => {
                    block.setPermutation(block.permutation.withState('pcr:ismossy', 1))
                    decrementstack(item, user, inv, "pcr:mossclump")
                    user.runCommandAsync('playsound use.moss @p ~ ~ ~')
                })
            }
        }
    }
})

// courtesy of fatalconfuzion (discord)
function getTimeSinceLastClick(entity) {
    const entityTimeStamp = entity[Symbol.for('dateStamp')] ?? 0;
    entity[Symbol.for('dateStamp')] = Date.now();
    return entity[Symbol.for('dateStamp')] - entityTimeStamp;
}

// courtesy of gst378 (discord)
function getDirection(itemLocation, playerLocation) {
    const x = playerLocation.x - itemLocation.x,
        y = playerLocation.y - itemLocation.y,
        z = playerLocation.z - itemLocation.z,
        d = Math.sqrt(x * x + y * y + z * z);
    return d ? { x: x / d, y: y / d, z: z / d } : { x: 0, y: 0, z: 0 };
}

export function buildmushroom(block, user) {
    let randomnumber = Math.floor(Math.random() * 2) + 2
    let size = 1
    user.runCommandAsync('fill ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z) + ' ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z) + ' brown_mushroom_block' + '["huge_mushroom_bits" = 10] replace ' + 'pcr:mb_gloomyshroom')
    user.runCommandAsync('fill ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z) + ' ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + randomnumber) + ' ' + JSON.stringify(block.location.z) + ' brown_mushroom_block' + '["huge_mushroom_bits" = 10] replace ' + 'minecraft:air')
    for (let i = 0; i < Math.floor(Math.random() * 3) + 1; i++) {
        user.runCommandAsync('fill ' + JSON.stringify(block.location.x + size) + ' ' + JSON.stringify(block.location.y + randomnumber + i) + ' ' + JSON.stringify(block.location.z + size) + ' ' + JSON.stringify(block.location.x - size) + ' ' + JSON.stringify(block.location.y + randomnumber + i) + ' ' + JSON.stringify(block.location.z - size) + ' mb:gloomyshroom_block' + ' replace ' + 'minecraft:air')
        size = size + 1
    }
}


function random_fill(eventData, user, floor, foliage, wood, mushroom, sand, snow, coalore) {
    const block = eventData.block
    const blockpos = { x: block.location.x, y: block.location.y, z: block.location.z }
    world.getDimension("overworld").getBlock(blockpos)
    var slowx = block.location.x
    var slowz = block.location.z
    var blockamount = 0
    for (let i = 0; i < 81; i++) {
        system.runTimeout(() => {
            user.runCommandAsync('fill ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y - 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y + 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + floor[Math.floor(Math.random() * 3)] + ' replace ' + 'minecraft:grass')
            user.runCommandAsync('fill ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y - 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y + 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + foliage[Math.floor(Math.random() * 2)] + ' replace ' + 'minecraft:tallgrass')
            user.runCommandAsync('fill ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y - 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y + 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + wood[Math.floor(Math.random() * 2)] + ' replace ' + 'minecraft:log')
            user.runCommandAsync('fill ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y - 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y + 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + wood[Math.floor(Math.random() * 2)] + ' replace ' + 'minecraft:log2')
            user.runCommandAsync('fill ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y - 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y + 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + mushroom[Math.floor(Math.random() * 0)] + ' replace ' + 'minecraft:brown_mushroom')
            user.runCommandAsync('fill ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y - 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y + 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + sand[Math.floor(Math.random() * 3)] + ' replace ' + 'minecraft:sand')
            user.runCommandAsync('fill ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y - 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y + 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + snow[Math.floor(Math.random() * 3)] + ' replace ' + 'minecraft:snow')
            user.runCommandAsync('fill ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y - 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + JSON.stringify(slowx - 4) + ' ' + JSON.stringify(block.location.y + 3) + ' ' + JSON.stringify(slowz - 4) + ' ' + coalore[Math.floor(Math.random() * 3)] + ' replace ' + 'minecraft:coal_ore')
            slowx = slowx + 1
            blockamount = blockamount + 1
            if (blockamount % 9 == 0) {
                slowz = slowz + 1
                slowx = slowx - 9
            }
        }, 5 * i)
    }
}