import * as Blockly from 'blockly';
// The purpose of this is to allow blocks to register for changes only of their type and the events they care about
// warning - only one change listener per block type is allowed. a second one will overwrite it.
type CallbackFunctionBlockType = (block: Blockly.Block, blockEvent : Blockly.Events.BlockBase) => void;
let registeredCallbacks = new Map<string, [string[], CallbackFunctionBlockType]>;
let blockEvents = [Blockly.Events.BLOCK_CHANGE, Blockly.Events.BLOCK_CREATE, Blockly.Events.BLOCK_DELETE, Blockly.Events.BLOCK_MOVE];
export function registerCallback(blockType : string, blockEvents : string[], func : CallbackFunctionBlockType){
registeredCallbacks.set(blockType, [blockEvents, func]);
}
function changeListener(e: Blockly.Events.Abstract){
if (blockEvents.includes(e.type as any)){
let eventBlockBase = (e as Blockly.Events.BlockBase);
let workspace = Blockly.Workspace.getById(eventBlockBase.workspaceId!)
let block = workspace?.getBlockById(eventBlockBase.blockId!)!
if(!block){
return;
}
let callbackInfo = registeredCallbacks.get(block.type);
if(!callbackInfo){
return;
}
if(callbackInfo[0].includes(e.type)){
callbackInfo[1](block, eventBlockBase);
}
}
}
export const setup = function (workspace: Blockly.Workspace) {
workspace.addChangeListener(changeListener);
}