import { world, system, TimeOfDay, TicksPerSecond, ItemStack, DimensionTypes, EquipmentSlot } from '@minecraft/server';
import * as blockBeforeOnPlayerPlace from './custom-components/before-on-player-place';
import * as blockOnPlayerInteract from './custom-components/on-interact';
import * as blockOnPlayerDestroy from './custom-components/on-destroy';
import * as blockOnRandomTick from './custom-components/on-random-tick';
import * as blockOnTick from './custom-components/on-tick';
import * as book from './book';
import { decrementStack } from './utils/helper';
world.afterEvents.worldInitialize.subscribe((eventData) => {
    if (world.getDynamicProperty('bf_dc:enchantments_axe') === undefined) {
        world.setDynamicProperty('bf_dc:enchantments_axe', JSON.stringify({}));
    }
    if (world.getDynamicProperty('bf_dc:enchantments') === undefined) {
        world.setDynamicProperty('bf_dc:enchantments', JSON.stringify({}));
    }
});
world.beforeEvents.worldInitialize.subscribe((eventData) => {
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_bench', new blockBeforeOnPlayerPlace.bench());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_full', new blockBeforeOnPlayerPlace.full());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_chair', new blockBeforeOnPlayerPlace.chair());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_armchair', new blockBeforeOnPlayerPlace.armchair());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_half', new blockBeforeOnPlayerPlace.half());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_full_horizontal', new blockBeforeOnPlayerPlace.fullHorizontal());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_full_without', new blockBeforeOnPlayerPlace.fullWithout());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_player_interact_flower_bed', new blockOnPlayerInteract.flowerBed());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_player_destroy_flower_bed', new blockOnPlayerDestroy.flowerBed());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_player_interact_hanging_sign', new blockOnPlayerInteract.hangingSign());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_table', new blockBeforeOnPlayerPlace.table());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_slab', new blockBeforeOnPlayerPlace.slab());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_tub', new blockBeforeOnPlayerPlace.tub());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_wardrobe_closet', new blockBeforeOnPlayerPlace.wardrobe());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_crate', new blockBeforeOnPlayerPlace.crate());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_backpack', new blockBeforeOnPlayerPlace.backpack());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_bed', new blockBeforeOnPlayerPlace.bed());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_random_tick_pepper', new blockOnRandomTick.pepper());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_player_interact_pepper', new blockOnPlayerInteract.pepper());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_player_interact_berry', new blockOnPlayerInteract.berry());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_player_interact_cauliflower', new blockOnPlayerInteract.cauliflower());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_player_interact_blinds', new blockOnPlayerInteract.blinds());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_player_interact_decorative_sword_utility', new blockOnPlayerInteract.sword());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_player_interact_axe_utility', new blockOnPlayerInteract.axe());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_player_interact_mug', new blockOnPlayerInteract.mug());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_cage', new blockBeforeOnPlayerPlace.cage());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_minus_slab', new blockBeforeOnPlayerPlace.minusSlab());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_piano', new blockBeforeOnPlayerPlace.piano());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_door_bell', new blockBeforeOnPlayerPlace.doorBell());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_fireplace', new blockBeforeOnPlayerPlace.fireplace());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_flag', new blockBeforeOnPlayerPlace.flag());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_fountain', new blockBeforeOnPlayerPlace.fountain());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_grandpa_clock', new blockBeforeOnPlayerPlace.grandpaClock());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_balloon', new blockBeforeOnPlayerPlace.balloon());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_knight', new blockBeforeOnPlayerPlace.knight());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_long_table', new blockBeforeOnPlayerPlace.longTable());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_mailbox', new blockBeforeOnPlayerPlace.mailbox());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_medium_table', new blockBeforeOnPlayerPlace.mediumTable());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_before_on_player_place_sofa', new blockBeforeOnPlayerPlace.sofa());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_tick_falling_leaves', new blockOnTick.fallingLeaves());
    eventData.blockComponentRegistry.registerCustomComponent('bf_dc:block_on_tick_falling_leaves_2', new blockOnTick.fallingLeaves2());
});
function includesSubstring(str, map) {
    for (let value of map.values())
        if (str.includes(value))
            return true;
    return false;
}
let french = false;
let english = false;
let portugese = false;
let spanish = false;
let german = false;
world.afterEvents.playerSpawn.subscribe((eventData) => {
    const player = eventData.player;
    if (player.hasTag('started'))
        return;
    player.runCommand(`tellraw @s {"rawtext":[{"text":"§b[!]§e Decoration Addon §f has been added.\nOpen the §cDaily paper§r for more information!"}]}`);
    const entity = player.dimension.spawnItem(new ItemStack('bf_dc:news_paper6'), { x: player.location.x + 10, y: player.location.y + 10, z: player.location.z + 10 });
    entity.runCommand(`execute if entity @s[type=item,name="Daily Paper"] run give @a[tag=!started] bf_dc:news_paper`);
    entity.runCommand(`execute if entity @s[type=item,name="Journal Quotidien"] run give @a[tag=!started] bf_dc:news_paper2`);
    entity.runCommand(`execute if entity @s[type=item,name="Tägliche Zeitung"] run give @a[tag=!started] bf_dc:news_paper3`);
    entity.runCommand(`execute if entity @s[type=item,name="Jornal Diário"] run give @a[tag=!started] bf_dc:news_paper4`);
    entity.runCommand(`execute if entity @s[type=item,name="Diario"] run give @a[tag=!started] bf_dc:news_paper5`);
    entity.runCommand(`execute if entity @s[type=item,name="Daily Paper"] run tag @s add bf_dc_english`);
    entity.runCommand(`execute if entity @s[type=item,name="Journal Quotidien"] run tag @s add bf_dc_french`);
    entity.runCommand(`execute if entity @s[type=item,name="Tägliche Zeitung"] run tag @s add bf_dc_german`);
    entity.runCommand(`execute if entity @s[type=item,name="Jornal Diário"] run tag @s add bf_dc_portuguese`);
    entity.runCommand(`execute if entity @s[type=item,name="Diario"] run tag @s add bf_dc_spanish`);

    if (english == false && french == false && spanish == false && portugese == false && german == false){
		if (entity.hasTag("bf_dc_english"))
			english = true;
		if (entity.hasTag("bf_dc_french"))
			french = true;
		if (entity.hasTag("bf_dc_spanish"))
			spanish = true;
		if (entity.hasTag("bf_dc_portuguese"))
			portugese = true;
		if (entity.hasTag("bf_dc_german"))
			german = true;
	}
    entity.remove();
    player.addTag('started');
});
async function mainLoop()
{
	if (english){
		await book.giveEnglishBook();
	}
	if (french){
		await book.giveFrenchBook();
	}
	if (spanish){
		await book.giveSpanishBook();
	}
	if (portugese){
		await book.givePortugeseBook();
	}
	if (german){
		await book.giveGermanBook();
	}
    system.run(mainLoop);
}
system.run(mainLoop);

world.beforeEvents.itemUseOn.subscribe((eventData) => {
    const heldItem = eventData.itemStack;
    const block = eventData.block;
    const permutation = block.permutation;
    if (block.permutation.matches('minecraft:air') ||
        heldItem.typeId != 'minecraft:water_bucket' ||
        !permutation.matches('bf_dc:null'))
        return;
    eventData.cancel = true;
});
const ENTITY_UTILITY = new Map();
ENTITY_UTILITY.set('bf_dc:christmas_present_utility', 'Christmas Present');
ENTITY_UTILITY.set('bf_dc:mailbox_utility', 'Mailbox');
ENTITY_UTILITY.set('bf_dc:cabinet_utility', 'Cabinet');
ENTITY_UTILITY.set('bf_dc:tool_box_utility', 'Tool Box');
ENTITY_UTILITY.set('bf_dc:wardrobe_closet_utility', 'Wardrobe Closet');
ENTITY_UTILITY.set('bf_dc:wooden_crate_utility', 'Wooden Crate');
world.afterEvents.entitySpawn.subscribe((eventData) => {
    const entity = eventData.entity;
    if (ENTITY_UTILITY.has(entity.typeId))
        entity.nameTag = ENTITY_UTILITY.get(entity.typeId);
});
const ENTITY_LIGHT = [
    'candle_holder',
    'candelabra',
    'chandelier',
    'ceiling_lamp',
    'oil_lamp'
];
system.runInterval(() => {
    const players = world.getAllPlayers();
    for (let player of players) {
        const dimension = player.dimension;
        // Check for knight statues
        const statues = dimension.getEntities({
            location: player.location,
            type: 'bf_dc:knight_statue'
        });
        for (let statue of statues) {
            const entitiesNearby = dimension.getEntities({
                location: statue.location,
                minDistance: 0,
                maxDistance: 2
            });
            for (let entity of entitiesNearby) {
                if (entity.typeId != 'minecraft:player' &&
                    entity.typeId != 'minecraft:item' &&
                    entity.typeId.startsWith('minecraft:')) {
                    statue.triggerEvent('anim');
                    entity.applyDamage(1);
                    entity.applyImpulse({
                        x: statue.location.x > entity.location.x ? -0.05 : 0.05,
                        y: statue.location.y > entity.location.y ? -0.05 : 0.05,
                        z: statue.location.z > entity.location.z ? -0.05 : 0.05
                    });
                }
            }
        }
        // Check for light entities
        const entities = player.dimension.getEntities({
            excludeTypes: ['minecraft:player']
        });
        for (let entity of entities) {
            const skin_id_component = entity.getComponent('minecraft:skin_id');
            if (includesSubstring(entity.typeId, ENTITY_LIGHT)) {
                if (skin_id_component === undefined)
                    continue;
                const skin_id = skin_id_component.value;
                if (skin_id == 0)
                    entity.runCommand(`fill ~~~ ~~~ air replace light_block`);
                else if (skin_id == 1)
                    dimension
                        .getBlock(entity.location)
                        .setType('minecraft:light_block_9');
            }
            else if (entity.typeId == 'bf_dc:cooking_campfire' ||
                entity.typeId == 'bf_dc:wall_mounted_torch' ||
                entity.typeId == 'bf_dc:wall_lantern')
                dimension
                    .getBlock(entity.location)
                    .setType('minecraft:light_block_10');
            else if (entity.typeId == 'bf_dc:string_light')
                dimension
                    .getBlock(entity.location)
                    .setType('minecraft:light_block_7');
            else if (entity.typeId == 'bf_dc:cooking_campfire')
                dimension
                    .getBlock(entity.location)
                    .setType('minecraft:light_block_10');
            else if (entity.typeId.includes('fireplace'))
                dimension
                    .getBlock(entity.location)
                    .setType('minecraft:light_block_10');
            else if (entity.typeId == 'bf_dc:sit') {
                const belowBlock = entity.dimension.getBlock({
                    x: entity.location.x,
                    y: entity.location.y - 0.3,
                    z: entity.location.z
                });
                if (belowBlock.typeId == 'minecraft:air')
                    entity.remove();
            }
        }
    }
    // Furnitures
    const furnitures = [];
    DimensionTypes.getAll().forEach((dimensionType) => {
        furnitures.push(...world
            .getDimension(dimensionType.typeId)
            .getEntities({ families: ['bf_dc_has_animations'] }));
    });
    try {
        for (const furniture of furnitures) {
            const players = furniture.dimension.getEntities({
                type: 'minecraft:player',
                location: furniture.location,
                maxDistance: 7
            });
            if (!players)
                continue;
            for (const player of players) {
                const familyComponent = furniture.getComponent('minecraft:type_family');
                if (!familyComponent)
                    continue;
                const lookAtBlock = player.getBlockFromViewDirection({
                    includeTypes: ['bf_dc:full', 'bf_dc:null3', 'bf_dc:slab'],
                    maxDistance: 7
                });
                if (!lookAtBlock) {
                    furniture.removeTag('bf_dc_is_looked_at');
                    continue;
                }
                const loc = lookAtBlock.block.center();
                let entity = furniture.dimension.getEntities({
                    families: ['bf_dc_has_animations'],
                    location: loc,
                    maxDistance: 1,
                    closest: 1
                })[0];
                if (!entity) {
                    entity = furniture.dimension.getEntities({
                        families: ['bf_dc_has_animations'],
                        location: { x: loc.x, y: loc.y - 1, z: loc.z },
                        maxDistance: 1,
                        closest: 1
                    })[0];
                }
                if (!entity) {
                    entity = furniture.dimension.getEntities({
                        families: ['bf_dc_has_animations'],
                        location: { x: loc.x, y: loc.y - 2, z: loc.z },
                        maxDistance: 1,
                        closest: 1
                    })[0];
                }
                if (entity && entity.id === furniture.id) {
                    player.addTag('bf_dc_look_at_furniture');
                    furniture.addTag('bf_dc_is_looked_at');
                }
                else
                    furniture.removeTag('bf_dc_is_looked_at');
            }
        }
    }
    catch (error) {
        console.error(error);
    }
});
world.afterEvents.dataDrivenEntityTrigger.subscribe((eventData) => {
    const eventId = eventData.eventId;
    const entity = eventData.entity;
    if (eventId != 'loot')
        return;
    if (entity.typeId.startsWith('bf_dc:') &&
        ENTITY_UTILITY.has(entity.typeId)) {
        const inventory = eventData.entity.getComponent('minecraft:inventory').container;
        for (let slot = 0; slot < inventory.size; slot++) {
            const item = inventory.getItem(slot);
            if (item)
                eventData.entity.dimension.spawnItem(item.clone(), eventData.entity.location);
        }
    }
    if (entity.typeId.startsWith('bf_dc:') && entity.typeId.includes('bed')) {
        const benchEntities = entity.dimension.getEntities({
            excludeTypes: ['minecraft:player'],
            type: 'bf_dc:sit',
            tags: ['bed'],
            location: entity.location,
            closest: 4
        });
        for (const entity of benchEntities)
            entity.remove();
    }
});
function playerSleep(player, entity) {
    const location = player.location;
    player.camera.fade({
        fadeColor: { blue: 0, green: 0, red: 0 },
        fadeTime: { fadeInTime: 2, fadeOutTime: 0.5, holdTime: 2 }
    });
    system.runTimeout(() => {
        player.setSpawnPoint({
            dimension: player.dimension,
            x: location.x,
            y: location.y,
            z: location.z
        });
        world.setTimeOfDay(TimeOfDay.Day);
        entity.getComponent('minecraft:rideable').ejectRiders();
    }, 2.5 * TicksPerSecond);
}
system.afterEvents.scriptEventReceive.subscribe((event) => {
    const id = event.id;
    const sourceEntity = event.sourceEntity;
    const dimension = sourceEntity.dimension;
    if (id == 'bf_dc:sleep') {
        if (world.getTimeOfDay() < TimeOfDay.Night)
            return;
        if (dimension.id != 'minecraft:overworld')
            return;
        const entities = sourceEntity.dimension.getEntitiesAtBlockLocation(sourceEntity.location);
        const block = sourceEntity.dimension.getBlock({
            x: sourceEntity.location.x,
            y: sourceEntity.location.y - 0.5,
            z: sourceEntity.location.z
        });
        for (let entity of entities) {
            if (block.typeId == 'bf_dc:bed_null') {
                if (entity.typeId == 'minecraft:player') {
                    playerSleep(entity, sourceEntity);
                    break;
                }
            }
        }
    }
    else if (id == 'bf_dc:skeleton' && event.message == 'equip') {
        event.sourceEntity.dimension
            .getEntities({
            location: event.sourceEntity.location,
            closest: 1,
            type: 'minecraft:player'
        })
            .forEach((player) => {
            let item = player.getComponent('equippable').getEquipment(EquipmentSlot.Mainhand);
            if (item == undefined)
                return;
            decrementStack(player);
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 ' +
                item.typeId);
            event.sourceEntity.setDynamicProperty('bf_dc:skeleton_arm', item.typeId);
        });
    }
    else if (id == 'bf_dc:skeleton' && event.message == 'unequip') {
        if (event.sourceEntity.getDynamicProperty('bf_dc:skeleton_arm') ==
            undefined)
            return;
        let item = event.sourceEntity.getDynamicProperty('bf_dc:skeleton_arm');
        sourceEntity.dimension.spawnItem(new ItemStack(item), sourceEntity.location);
    }
    else if (id == 'bf_dc:sauce_pan' && event.message == 'beef') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:beef');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_beef');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_beef'), event.sourceEntity.location);
            }, 20);
        }, 20 * 5);
    }
    else if (id == 'bf_dc:sauce_pan' && event.message == 'porkchop') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:porkchop');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_porkchop');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_porkchop'), event.sourceEntity.location);
            }, 20);
        }, 20 * 5);
    }
    else if (id == 'bf_dc:sauce_pan' && event.message == 'chicken') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:chicken');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_chicken');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_chicken'), event.sourceEntity.location);
            }, 20);
        }, 20 * 5);
    }
    else if (id == 'bf_dc:sauce_pan' && event.message == 'cod') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cod');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_cod');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_cod'), event.sourceEntity.location);
            }, 20);
        }, 20 * 5);
    }
    else if (id == 'bf_dc:sauce_pan' && event.message == 'salmon') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:salmon');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_salmon');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_salmon'), event.sourceEntity.location);
            }, 20);
        }, 20 * 5);
    }
    else if (id == 'bf_dc:sauce_pan' && event.message == 'mutton') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:mutton');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_mutton');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_mutton'), event.sourceEntity.location);
            }, 20);
        }, 20 * 5);
    }
    else if (id == 'bf_dc:sauce_pan' && event.message == 'rabbit') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:rabbit');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_rabbit');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_rabbit'), event.sourceEntity.location);
            }, 20);
        }, 20 * 5);
    }
    else if (id == 'bf_dc:sauce_pan2' && event.message == 'beef') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:beef');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_beef');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_beef'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.25);
    }
    else if (id == 'bf_dc:sauce_pan2' && event.message == 'porkchop') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:porkchop');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_porkchop');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_porkchop'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.25);
    }
    else if (id == 'bf_dc:sauce_pan2' && event.message == 'chicken') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:chicken');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_chicken');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_chicken'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.25);
    }
    else if (id == 'bf_dc:sauce_pan2' && event.message == 'cod') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cod');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_cod');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_cod'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.25);
    }
    else if (id == 'bf_dc:sauce_pan2' && event.message == 'salmon') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:salmon');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_salmon');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_salmon'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.25);
    }
    else if (id == 'bf_dc:sauce_pan2' && event.message == 'mutton') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:mutton');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_mutton');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_mutton'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.25);
    }
    else if (id == 'bf_dc:sauce_pan2' && event.message == 'rabbit') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:rabbit');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_rabbit');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_rabbit'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.25);
    }
    else if (id == 'bf_dc:sauce_pan3' && event.message == 'beef') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:beef');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_beef');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_beef'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.04);
    }
    else if (id == 'bf_dc:sauce_pan3' && event.message == 'porkchop') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:porkchop');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_porkchop');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_porkchop'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.04);
    }
    else if (id == 'bf_dc:sauce_pan3' && event.message == 'chicken') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:chicken');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_chicken');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_chicken'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.04);
    }
    else if (id == 'bf_dc:sauce_pan3' && event.message == 'cod') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cod');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_cod');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_cod'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.04);
    }
    else if (id == 'bf_dc:sauce_pan3' && event.message == 'salmon') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:salmon');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_salmon');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_salmon'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.04);
    }
    else if (id == 'bf_dc:sauce_pan3' && event.message == 'mutton') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:mutton');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_mutton');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_mutton'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.04);
    }
    else if (id == 'bf_dc:sauce_pan3' && event.message == 'rabbit') {
        event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:rabbit');
        system.runTimeout(() => {
            event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:cooked_rabbit');
            system.runTimeout(() => {
                event.sourceEntity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 minecraft:air');
                event.sourceEntity.dimension.spawnItem(new ItemStack('minecraft:cooked_rabbit'), event.sourceEntity.location);
            }, 20);
        }, 20 * 2.04);
    }
});
const substrings = [
    'gramophone',
    'standing_ladder',
    'terracotta_vase',
    'toilet',
    'cage',
    'candelabra',
    'fountain',
    'heart_balloon',
    'mailbox',
    'snake',
    'cactus',
    'rubber',
    'christmas_tree',
    'mop',
    'scarecrow',
    'snowman_statue',
    'tomato_plant',
    'training_dummy'
];
world.beforeEvents.entityRemove.subscribe((eventData) => {
    const entity = eventData.removedEntity;
    if (!entity.typeId.startsWith('bf_dc:'))
        return;
    const dimension = entity.dimension;
    const location = entity.location;
    const entityTypeId = entity.typeId;
    const includesAny = substrings.some((substring) => entityTypeId.includes(substring));
    const includesMirrorWithoutWall = entityTypeId.includes('mirror') && !entityTypeId.includes('wall');
    const includesFlagWithoutRope = entityTypeId.includes('flag') && !entityTypeId.includes('rope');
    if (includesAny || includesMirrorWithoutWall || includesFlagWithoutRope)
        system.run(() => {
            dimension.setBlockType({ x: location.x, y: location.y + 1, z: location.z }, 'minecraft:air');
        });
    else if (entityTypeId.includes('grandpa_clock') ||
        entityTypeId.includes('knight_statue')) {
        system.run(() => {
            dimension.setBlockType({ x: location.x, y: location.y + 1, z: location.z }, 'minecraft:air');
            dimension.setBlockType({ x: location.x, y: location.y + 2, z: location.z }, 'minecraft:air');
        });
    }
    else if (entityTypeId.includes('string'))
        dimension.runCommandAsync(`setblock ${location.x} ${location.y} ${location.z} air destroy`);
    else if (entityTypeId.includes('campfire'))
        dimension.runCommandAsync(`setblock ${location.x} ${location.y + 1} ${location.z} air replace`);
    dimension.runCommandAsync(`setblock ${location.x} ${location.y} ${location.z} air`);
});
const TABLE_REGEX = new RegExp('bf_dc:[a-z]\\w+_table\\b');
const TUB_REGEX = new RegExp('bf_dc:[a-z]\\w+_tub\\b');
world.beforeEvents.playerBreakBlock.subscribe((eventData) => {
    const block = eventData.block;
    const dimension = block.dimension;
    const location = block.location;
    if (block.typeId == 'bf_dc:bench_slab') {
        const benchEntities = dimension.getEntities({
            excludeTypes: ['minecraft:player'],
            type: 'bf_dc:sit',
            tags: ['bench'],
            location: location,
            closest: 2
        });
        const benchEntity = dimension.getEntities({
            excludeTypes: ['minecraft:player'],
            location: location,
            closest: 2
        });
        for (const entity of benchEntities)
            system.run(() => {
                dimension.setBlockType(location, 'minecraft:air');
                entity.remove();
            });
        for (const entity of benchEntity)
            if (entity.typeId.includes('bench'))
                system.run(() => {
                    entity.triggerEvent('loot');
                });
    }
    if (block.typeId == 'bf_dc:null') {
        const permutation = block.permutation.getState('minecraft:cardinal_direction');
        const tableEntities = block.dimension.getEntities({
            excludeTypes: ['minecraft:player'],
            location: block.location,
            closest: 1
        });
        for (const entity of tableEntities) {
            if (TABLE_REGEX.test(entity.typeId)) {
                const location = entity.getDynamicProperty('bf_dc:table_location');
                system.run(() => {
                    if (permutation == 'north')
                        entity.runCommand(`fill ${location.x + 1} ${location.y} ${location.z + 1} ${location.x - 1} ${location.y} ${location.z} air replace bf_dc:null`);
                    else if (permutation == 'south')
                        entity.runCommand(`fill ${location.x - 1} ${location.y} ${location.z - 1} ${location.x + 1} ${location.y} ${location.z} air replace bf_dc:null`);
                    else if (permutation == 'east')
                        entity.runCommand(`fill ${location.x - 1} ${location.y} ${location.z + 1} ${location.x} ${location.y} ${location.z - 1} air replace bf_dc:null`);
                    else if (permutation == 'west')
                        entity.runCommand(`fill ${location.x + 1} ${location.y} ${location.z - 1} ${location.x} ${location.y} ${location.z + 1} air replace bf_dc:null`);
                    entity.triggerEvent('loot');
                });
            }
            else if (TUB_REGEX.test(entity.typeId)) {
                const location = entity.getDynamicProperty('bf_dc:tub_location');
                system.run(() => {
                    if (permutation == 'north')
                        entity.runCommand(`fill ${location.x} ${location.y} ${location.z} ${location.x - 1} ${location.y} ${location.z + 1} air replace bf_dc:null`);
                    else if (permutation == 'south')
                        entity.runCommand(`fill ${location.x} ${location.y} ${location.z} ${location.x + 1} ${location.y} ${location.z - 1} air replace bf_dc:null`);
                    else if (permutation == 'east')
                        entity.runCommand(`fill ${location.x} ${location.y} ${location.z} ${location.x - 1} ${location.y} ${location.z - 1} air replace bf_dc:null`);
                    else if (permutation == 'west')
                        entity.runCommand(`fill ${location.x} ${location.y} ${location.z} ${location.x + 1} ${location.y} ${location.z + 1} air replace bf_dc:null`);
                    entity.triggerEvent('loot');
                });
            }
        }
    }
    if (block.typeId == 'bf_dc:full') {
        const permutation = block.permutation.getState('minecraft:cardinal_direction');
        const tableEntities = block.dimension.getEntities({
            excludeTypes: ['minecraft:player'],
            location: block.location,
            closest: 1
        });
        for (const entity of tableEntities) {
            const location = entity.getDynamicProperty('bf_dc:crate_location');
            system.run(() => {
                if (permutation == 'north')
                    entity.runCommand(`fill ${location.x + 1} ${location.y} ${location.z + 1} ${location.x - 1} ${location.y} ${location.z} air replace bf_dc:full`);
                else if (permutation == 'south')
                    entity.runCommand(`fill ${location.x - 1} ${location.y} ${location.z - 1} ${location.x + 1} ${location.y} ${location.z} air replace bf_dc:full`);
                else if (permutation == 'east')
                    entity.runCommand(`fill ${location.x - 1} ${location.y} ${location.z + 1} ${location.x} ${location.y} ${location.z - 1} air replace bf_dc:full`);
                else if (permutation == 'west')
                    entity.runCommand(`fill ${location.x + 1} ${location.y} ${location.z - 1} ${location.x} ${location.y} ${location.z + 1} air replace bf_dc:full`);
                entity.triggerEvent('loot');
            });
        }
    }
    if (block.typeId.startsWith('bf_dc:armchair_') ||
        block.typeId.startsWith('_chair')) {
        const benchEntities = dimension.getEntities({
            excludeTypes: ['minecraft:player'],
            type: 'bf_dc:sit',
            tags: ['bench'],
            location: location,
            closest: 1
        });
        for (const entity of benchEntities)
            system.run(() => {
                entity.remove();
            });
    }
    if (block.typeId == 'bf_dc:bed_null') {
        const permutation = block.permutation.getState('minecraft:cardinal_direction');
        const tableEntities = block.dimension.getEntities({
            excludeTypes: ['minecraft:player'],
            location: location,
            closest: 1
        });
        for (const entity of tableEntities) {
            const location = entity.getDynamicProperty('bf_dc:bed_location');
            system.run(() => {
                if (permutation == 'north')
                    entity.runCommand(`fill ${location.x + 1} ${location.y} ${location.z + 1} ${location.x} ${location.y} ${location.z - 1} air replace bf_dc:bed_null`);
                else if (permutation == 'south')
                    entity.runCommand(`fill ${location.x - 1} ${location.y} ${location.z - 1} ${location.x + 0.5} ${location.y} ${location.z + 1} air replace bf_dc:bed_null`);
                else if (permutation == 'east')
                    entity.runCommand(`fill ${location.x - 1} ${location.y} ${location.z} ${location.x + 1} ${location.y} ${location.z + 1} air replace bf_dc:bed_null`);
                else if (permutation == 'west')
                    entity.runCommand(`fill ${location.x + 1} ${location.y} ${location.z + 1} ${location.x - 1} ${location.y} ${location.z} air replace bf_dc:bed_null`);
                entity.triggerEvent('loot');
            });
        }
    }
});
world.afterEvents.entityHitEntity.subscribe((eventData) => {
    if (eventData.hitEntity.typeId != 'bf_dc:training_dummy')
        return;
    eventData.hitEntity.dimension.spawnParticle('minecraft:critical_hit_emitter', {
        x: eventData.hitEntity.location.x,
        y: eventData.hitEntity.location.y + 1.75,
        z: eventData.hitEntity.location.z
    });
});
