import { world, BlockPermutation, Dimension, Block, system, ItemStack } from "@minecraft/server";
import { bush_Manager } from './fence_Manager_rns'
import { itemDurability, itemAttack, itemMine } from './itemDurability'


world.afterEvents.itemUse.subscribe((eventData) => {
    let item = eventData.itemStack
    let player = eventData.source
    let block = player.getBlockFromViewDirection()?.block
    const inv = player.getComponent("minecraft:inventory").container
    const slot = player.selectedSlotIndex

    //Strip If holding Axe
    if (item.hasTag("minecraft:is_axe")) {

        if (block.hasTag('rns:branch') && !block.typeId.match("_stripped")) {

            let direction = block.permutation.getState('minecraft:cardinal_direction')
            let north = block.permutation.getState('rns:north')
            let south = block.permutation.getState('rns:south')
            let west = block.permutation.getState('rns:west')
            let east = block.permutation.getState('rns:east')

            block.setPermutation(BlockPermutation.resolve(block.typeId + "_stripped"))

            if (!block.typeId.match('up')) {
                block.setPermutation(block.permutation.withState('minecraft:cardinal_direction', direction))
            }
            else {
                block.setPermutation(block.permutation.withState('rns:north', north))
                block.setPermutation(block.permutation.withState('rns:south', south))
                block.setPermutation(block.permutation.withState('rns:west', west))
                block.setPermutation(block.permutation.withState('rns:east', east))
            }

            player.playSound("fall.wood")
            adjustItemDamage(inv, item, 1, slot)
        }
    }

    // Bushes
    if (block?.permutation.getState('rns:snow') == 1 || block?.typeId == 'rns:snowazaleas') {
        if (item?.typeId == "minecraft:brush" || item?.hasTag('minecraft:is_shovel')) {
            if (block?.permutation.getState('rns:snow') == 1) {
                block.setPermutation(block.permutation.withState('rns:snow', 0))
            }
            if (block?.typeId == 'rns:snowazaleas') {
                block.setPermutation(BlockPermutation.resolve('minecraft:azalea'))
            }
            player.dimension.spawnParticle('minecraft:snowflake_particle', block.center())
        }
    }

    //Nimberry Bush
    if (block?.typeId == "rns:nimberrybush") {
        if (block.permutation.getState('rns:leaf') == 0) {
            if (item?.typeId == "minecraft:bone_meal") {
                decrementstack(item, player, "minecraft:bone_meal")
                block.setPermutation(block.permutation.withState('rns:leaf', 1))
                player.dimension.spawnParticle('minecraft:crop_growth_emitter', block.center())
            }
            if (item?.typeId == "rns:pinksalt") {
                block.setPermutation(BlockPermutation.resolve('rns:driedbush'))
                bush_Manager.updateBushesAround(block)
                player.runCommandAsync('playsound random.fizz @p ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z) + ' 0.5')
                decrementstack(item, player, "rns:pinksalt")
            }

        }
    }

    //Bush and Dried Bushes
    if (block?.typeId == "rns:bush" || block?.typeId == "rns:driedbush") {
        if (block.permutation.getState('rns:leaf') == 1) {
            if (item?.typeId == "minecraft:bone_meal") {
                decrementstack(item, player, "minecraft:bone_meal")
                block.setPermutation(block.permutation.withState('rns:leaf', 0))
                player.dimension.spawnParticle('minecraft:crop_growth_emitter', block.center())
            }
        }
        if (block.permutation.getState('rns:leaf') == 0) {
            if (item?.typeId == "rns:flintscraper") {
                block.setPermutation(block.permutation.withState('rns:leaf', 1))
                player.runCommandAsync('playsound block.sweet_berry_bush.break @p ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z))
                if (block.typeId == "rns:bush") {
                    player.runCommandAsync('loot spawn ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z) + ' loot leaf')
                }
                else if (block.typeId == "rns:driedbush") {
                    player.runCommandAsync('loot spawn ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z) + ' loot driedleaf')
                }
                else if (block.typeId == "rns:nimberrybush") {
                    player.runCommandAsync('loot spawn ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z) + ' loot driedleaf')
                }
            }

            if (item?.typeId == "rns:pinksalt" && block.typeId == "rns:bush") {
                block.setPermutation(BlockPermutation.resolve('rns:driedbush'))
                bush_Manager.updateBushesAround(block)
                player.runCommandAsync('playsound random.fizz @p ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z) + ' 0.5')
                decrementstack(item, player, "rns:pinksalt")
            }
        }
    }


})

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

    //Shears Stuff
    if (item?.typeId == "minecraft:shears") {
        if (blockname == "rns:bluetippedfern") {
            system.run(() => {
                summonitem("rns:bluetippedfernitem", 1, block, item, player, true)
            })
        }
        if (blockname == "rns:browntippedgrass") {
            system.run(() => {
                summonitem("rns:browntippedgrassitem", 1, block, item, player, true)
            })
        }
        if (blockname == "rns:windsweptgrass") {
            system.run(() => {
                summonitem("rns:windsweptgrassitem", 1, block, item, player, true)
            })
        }
        if (blockname == "rns:desertweeds") {
            system.run(() => {
                summonitem("rns:desertweedsitem", 1, block, item, player, true)
            })
        }
        if (blockname == "rns:beachgrass") {
            system.run(() => {
                summonitem("rns:beachgrassitem", 1, block, item, player, true)
            })
        }
        if (blockname == "rns:shortbeachwheat") {
            system.run(() => {
                summonitem("rns:shortbeachwheatitem", 1, block, item, player, true)
            })
        }
        if (blockname == "rns:beachbush") {
            system.run(() => {
                summonitem("rns:beachbushitem", 1, block, item, player, true)
            })
        }
        if (blockname == "rns:beachtallgrassbottom") {
            system.run(() => {
                summonitem("rns:beachtallgrassitem", 1, block, item, player, true)
            })
        }
        if (blockname == "rns:beachtallgrasswheatbottom") {
            system.run(() => {
                summonitem("rns:beachtallgrass_wheattippeditem", 1, block, item, player, true)
            })
        }
    }
    if (item?.typeId != 'minecraft:wooden_shovel' && item?.hasTag('minecraft:is_shovel') && block.typeId == 'rns:pinkrocksandore') {
        system.run(() => {
            adjustItemDamage(inv, item, 1, slot)
            player.runCommandAsync('loot spawn ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z) + ' loot rocksaltstoneore')
        })
    }
    if (item?.typeId != 'minecraft:wooden_pickaxe' && item?.hasTag('minecraft:is_pickaxe') && block.typeId == 'rns:pinkrockstoneore') {
        system.run(() => {
            adjustItemDamage(inv, item, 1, slot)
            player.runCommandAsync('loot spawn ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z) + ' loot rocksaltstoneore')
        })
    }
    if (block.typeId == 'rns:birdsnest') {
        lootOrSummon(block, player, 'chicken', 'birdsnest', 8)
    }
    if (block.typeId == 'rns:bonesand') {
        lootOrSummon(block, player, 'skeleton Sandy_Skeleton', 'bones', 12)
    }
    if (block.typeId == 'rns:phantomsnest') {
        lootOrSummon(block, player, 'phantom', 'phantomsnest', 24)
    }
})

world.afterEvents.entityHitEntity.subscribe((eventData) => {
    var player = eventData.damagingEntity
    var enemy = eventData.hitEntity
    var item = player?.getComponent('equippable')?.getEquipment('Mainhand')
    if (item?.typeId == "rns:mistletoebone") {
        enemy.addEffect('poison', 100)
    }
})



export function sifting(block, player, loot, item, req) {
    player.runCommandAsync('playsound block.composter.fill_success @p ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y) + ' ' + JSON.stringify(block.location.z) + ' 0.5')
    player.runCommandAsync('loot spawn ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z) + ' loot ' + loot)
    decrementstack(item, player, req)
}

export function lootOrSummon(block, player, summon, loot, chance) {
    let num = Math.round(Math.random() * chance)
    if (num < 1) {
        player.runCommandAsync('summon ' + summon + ' ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z))
    }
    else {
        player.runCommandAsync('loot spawn ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z) + ' loot ' + loot)
    }
}

export function adjustItemDamage(playerEquip, itemStack, damageToAdd, slot) {
    const durabilityComp = itemStack.getComponent('minecraft:durability');
    if (!durabilityComp) return;
    if (durabilityComp.damage === durabilityComp.maxDurability && playerEquip) {
        playerEquip.setItem(slot, undefined);
    } else {
        durabilityComp.damage = Math.min(durabilityComp.damage + damageToAdd, durabilityComp.maxDurability);
        if (durabilityComp.damage === durabilityComp.maxDurability) {
            playerEquip.setItem(slot, undefined);
        } else {
            playerEquip.setItem(slot, itemStack);
        }
    }
}

export function decrementstack(item, user, req) {
    system.run(() => {
        if (item?.typeId === req && item.amount > 1) {
            item.amount--;
            user.getComponent('equippable').setEquipment('Mainhand', item)
        }
        else if (item?.typeId === req && item.amount === 1) {
            user.getComponent('equippable').setEquipment('Mainhand', undefined)
        }
    })
}

export function summonitem(newitem, amount, block, item, player, should_take_durability) {
    const inv = player.getComponent("minecraft:inventory").container
    const slot = player.selectedSlotIndex

    let newitem2 = new ItemStack(newitem, amount)
    block.dimension.spawnItem(newitem2, { x: block.location.x + 0.5, y: block.location.y + 1, z: block.location.z + 0.5 })
    if (should_take_durability == true) {
        adjustItemDamage(inv, item, 1, slot)
    }
}

world.afterEvents.itemCompleteUse.subscribe((eventData) => {
    var item = eventData.itemStack
    var player = eventData.source
    if (item?.typeId == "rns:nimberry") {
        player.addEffect("speed", 60)
    }
    if (item?.typeId == "rns:aloeveraspine") {
        player.addEffect("fire_resistance", 600)
        player.addEffect("regeneration", 60)
        player.extinguishFire(true)
    }
    if (item?.typeId == "rns:nimberrybowl") {
        player.addEffect("speed", 120)
    }
    if (item?.typeId == "rns:pinetea") {
        player.removeEffect('slowness')
    }
})