import { world, system, Player } from '@minecraft/server';
import { setMacro, isMacroEnabled, setMacroEnabled } from '../util/macro_utils';
system.afterEvents.scriptEventReceive.subscribe((event)=>{
    if (event.id != 'jigsaw:macro') return;
    if (!event.sourceEntity || !(event.sourceEntity instanceof Player)) return;
    const message = event.message;
    const sender = event.sourceEntity;
    if (message == 'create') {
        createMacro(sender);
    }
    if (message == 'enable') {
        enableMacro(sender);
    }
    if (message == 'disable') {
        disableMacro(sender);
    }
});
function createMacro(sender) {
    const raycast = sender.getBlockFromViewDirection({
        blockFilter: {
            includeTypes: [
                'jigsaw:jigsaw_block'
            ]
        },
        includeLiquidBlocks: true,
        includePassableBlocks: true,
        maxDistance: 8
    });
    const block = raycast.block;
    if (!block) {
        sender.sendMessage('Failed to set jigsaw macro, no jigsaw block was found in range.');
        return;
    }
    const entities = sender.dimension.getEntitiesAtBlockLocation(block.location);
    const jigsawEntity = entities.find((entity)=>{
        return entity.typeId == 'jigsaw:jigsaw_data' && typeof entity.getDynamicProperty('jigsawData') == 'string';
    });
    if (!jigsawEntity) {
        world.sendMessage('Failed to set jigsaw macro, jigsaw data is invalid or missing.');
        return;
    }
    setMacro(sender, JSON.parse(jigsawEntity.getDynamicProperty('jigsawData')));
    sender.sendMessage('Jigsaw macro created.');
}
function enableMacro(sender) {
    if (isMacroEnabled(sender)) {
        sender.sendMessage('Jigsaw macro is already enabled.');
        return;
    }
    setMacroEnabled(sender, true);
    sender.sendMessage('Jigsaw macro successfully enabled.');
}
function disableMacro(sender) {
    if (!isMacroEnabled(sender)) {
        sender.sendMessage('Jigsaw macro is already disabled.');
        return;
    }
    setMacroEnabled(sender, false);
    sender.sendMessage('Jigsaw macro successfully disabled.');
}
