import { world ,system,GameMode,ItemStack} from "@minecraft/server"
import {oreDestroy} from "./ore_drop.js"
import { getScore } from "../utils/score.js"

/*
    WARNING:
        SHIT CODE AHEAD
        SHIT LEVEL:7/10

*/
   
const UnbreakListId = ["minecraft:air","minecraft:bedrock","minecraft:end_portal_frame","minecraft:reinforced_deepslate","edx:runic_chest"]
world.beforeEvents.playerBreakBlock.subscribe(ev => {
    const item = ev.itemStack
    const block = ev.block;
    const dimension = ev.dimension
    const player = ev.player
    oreDestroy(block,item,player,ev)
    //door
    const aboveBlock = block.above();
    const belowBlock = block.below();
    if (belowBlock.hasTag('edx:door') && block.hasTag('edx:door')) {
        system.runTimeout(() => {
            belowBlock.setType('minecraft:air');
        })
        
    } else if (aboveBlock.hasTag('edx:door') && block.hasTag('edx:door')) {
        system.runTimeout(() => {
            aboveBlock.setType('minecraft:air');
        })
    }
    //other
    TallPlantDestroy(block)
    oozeshroomFullDestroy(block)
    if (block.hasTag('no_silktouch') && !player.matches({ gameMode: GameMode.Creative }) && player?.getComponent('equippable')?.getEquipment('Mainhand')?.getComponent('enchantable')?.getEnchantment("silk_touch")?.level==1){
        ev.cancel = true
        var location = { x: ev.block.location.x, y: ev.block.location.y, z: ev.block.location.z };
        system.runTimeout(() => {
            ev.dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} air destroy`)
        })
    }
    if (item != undefined){
        if (block.typeId === 'minecraft:mob_spawner' && !player.matches({ gameMode: GameMode.Creative }))
        {
       var location = { x: ev.block.location.x, y: ev.block.location.y, z: ev.block.location.z };
       system.runTimeout(() => {
           ev.dimension.runCommand(`structure load spawner_loot ${location.x} ${location.y} ${location.z}`)
       }
    )
    }
    if(block.typeId == "edx:spotter")
    {
        if(player.matches({ gameMode: GameMode.Creative })) return;
        var itemdrop = ""
        const type = block.permutation.getState("edx:type");
        if(type == "fire_opal") itemdrop = 'edx:fire_opal'
        else if(type == "lapis") itemdrop = 'minecraft:lapis_lazuli'
        else if(type == "diamond") itemdrop = 'minecraft:diamond'
        else if(type == "amethyst") itemdrop = 'minecraft:amethyst_shard'
        else if(type == "ruby") itemdrop = 'edx:ruby'
        else if(type == "emerald") itemdrop = 'minecraft:emerald'
        else if(type == "quartz") itemdrop = 'minecraft:quartz'
        if(itemdrop!="")
        {
            system.runTimeout(() => {
                dimension.spawnItem(new ItemStack(itemdrop,1), block.location);
            },2)
        }
    }
    const pickMode = getScore(player,'mode')
    pickModes(item,pickMode,block,player)
    shovelModes(item,pickMode,block,player)


    
    }
})

function pickModes(item,pickMode,block,player){
    const face = player.getBlockFromViewDirection().face
    if((pickMode>=1 && item?.getTags()?.includes('pickaxe_tier1')) || (pickMode==1 && (item?.getTags()?.includes('pickaxe_tier2') || item?.getTags()?.includes('pickaxe_tier3'))))
    {
        if(!UnbreakListId.includes(block.below().typeId) || block.below().hasTag('edx:stone'))
            system.runTimeout(() => {
                
                blockDestroy(block.below(),item,player)
            })
    }
        

    else if((pickMode>=2 && item?.getTags()?.includes('pickaxe_tier2')) || (pickMode==2 && item?.getTags()?.includes('pickaxe_tier3')))
    {
        
        system.runTimeout(() => {
            if(face=='Down'|| face=='Up') var blocks = [block.north(),block.south(),block.west(),block.east()]
            else if(face=='West'|| face=='East') var blocks = [block.above(),block.north(),block.below(),block.south()]
            else if(face=='North'|| face=='South') var blocks = [block.above(),block.east(),block.below(),block.west()]

            for(const Block of blocks)
                if(!UnbreakListId.includes(Block.typeId) || Block.hasTag('edx:stone'))
                    system.runTimeout(() => {
                        blockDestroy(Block,item,player)
                    })
        })
    }
    else if(pickMode==3 && item?.getTags()?.includes('pickaxe_tier3'))
    {
        if(face=='Down'|| face=='Up') var blocks = [block.north(),block.south(),block.west(),block.east(),block.north().east(),block.north().west(),block.south().west(),block.south().east()]
        else if(face=='West'|| face=='East') var blocks = [block.above(),block.north(),block.below(),block.south(),block.north().above(),block.north().below(),block.south().above(),block.south().below()]
        else if(face=='North'|| face=='South') var blocks = [block.above(),block.east(),block.below(),block.west(),block.east().above(),block.east().below(),block.west().above(),block.west().below()]

        for(const Block of blocks)
            if(!UnbreakListId.includes(Block.typeId) || Block.hasTag('edx:stone'))
                system.runTimeout(() => {
                    blockDestroy(Block,item,player)
                })
    }
}

function shovelModes(item,pickMode,block,player){
    
    const face = player.getBlockFromViewDirection().face
    if((pickMode>=1 && item?.getTags()?.includes('shovel_tier1')) || (pickMode==1 && (item?.getTags()?.includes('shovel_tier2') || item?.getTags()?.includes('shovel_tier3'))))
    {
        if(shovelBreak.includes(block.below().typeId) || block.below().hasTag('edx:shovel'))
            system.runTimeout(() => {
                blockDestroyNoOre(block.below(),item,player)
            })
    }
    else if((pickMode>=2 && item?.getTags()?.includes('shovel_tier2')) || (pickMode==2 && item?.getTags()?.includes('shovel_tier3')))
    {
        system.runTimeout(() => {
            if(face=='Down'|| face=='Up') var blocks = [block.north(),block.south(),block.west(),block.east()]
            else if(face=='West'|| face=='East') var blocks = [block.above(),block.north(),block.below(),block.south()]
            else if(face=='North'|| face=='South') var blocks = [block.above(),block.east(),block.below(),block.west()]

            for(const Block of blocks)
                if(shovelBreak.includes(Block.typeId) || Block.hasTag('edx:shovel'))
                    system.runTimeout(() => {
                        blockDestroyNoOre(Block,item,player)
                    })
        })
    }
    else if(pickMode==3 && item?.getTags()?.includes('shovel_tier3'))
    {
        if(face=='Down'|| face=='Up') var blocks = [block.north(),block.south(),block.west(),block.east(),block.north().east(),block.north().west(),block.south().west(),block.south().east()]
        else if(face=='West'|| face=='East') var blocks = [block.above(),block.north(),block.below(),block.south(),block.north().above(),block.north().below(),block.south().above(),block.south().below()]
        else if(face=='North'|| face=='South') var blocks = [block.above(),block.east(),block.below(),block.west(),block.east().above(),block.east().below(),block.west().above(),block.west().below()]

        for(const Block of blocks)
            if(shovelBreak.includes(Block.typeId) || Block.hasTag('edx:shovel'))
                system.runTimeout(() => {
                        blockDestroyNoOre(Block,item,player)
                    })
    }

}

function oozeshroomFullDestroy(block)
{
    if(block?.permutation?.getState("edx:type")==="top" && block?.permutation?.getState("edx:juice")==="full") 
        system.runTimeout(() => {
        block.dimension.spawnParticle('edx:oozeshroom_full_destroy',block.below().center());
        },2)
    else if(block?.permutation?.getState("edx:juice")==="full")
        system.runTimeout(() => {
            block.dimension.spawnParticle('edx:oozeshroom_full_destroy',block.center());
            },2)
}
function TallPlantDestroy(block)
{
    const type = block.permutation.getState("edx:type")
    if(type==="top" && block.below()?.permutation?.getState("edx:type")=='bottom')
    {
        system.runTimeout(() => {
            block.below().setType('minecraft:air');
        })
    }
    else if(type==="bottom" && block.above()?.permutation?.getState("edx:type")=='top')
    {
        system.runTimeout(() => {
            block.above().setType('minecraft:air');
        })
       
    }
}

const shovelBreak = [
    "minecraft:clay",
    "minecraft:dirt",
    "minecraft:dirt_with_roots",
    "minecraft:coarse_dirt",
    "minecraft:black_concrete_powder",
    "minecraft:white_concrete_powder",
    "minecraft:gray_concrete_powder",
    "minecraft:light_gray_concrete_powder",
    "minecraft:blue_concrete_powder",
    "minecraft:brown_concrete_powder",
    "minecraft:cyan_concrete_powder",
    "minecraft:green_concrete_powder",
    "minecraft:light_blue_concrete_powder",
    "minecraft:lime_concrete_powder",
    "minecraft:magenta_concrete_powder",
    "minecraft:orange_concrete_powder",
    "minecraft:pink_concrete_powder",
    "minecraft:powder_snow",
    "minecraft:purple_concrete_powder",
    "minecraft:red_concrete_powder",
    "minecraft:yellow_concrete_powder",
    "minecraft:farmland",
    "minecraft:grass_block",
    "minecraft:grass_path",
    "minecraft:gravel",
    "minecraft:mud",
    "minecraft:mycelium",
    "minecraft:podzol",
    "minecraft:sand",
    "minecraft:red_sand",
    "minecraft:soul_sand",
    "minecraft:soul_soil",
    "minecraft:snow",
    "minecraft:snow_layer"
]

function blockDestroy(block,item,player){
    block.dimension.runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`)
    oreDestroy(block,item,player)
}
function blockDestroyNoOre(block,item,player){
    block.dimension.runCommand(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air destroy`)
}
