import { system, world, } from "@minecraft/server";
import { namespace } from "../../../config/_config";
import { summonEntitiesInRange } from "../../helper/summonFromLocation";
export class MarketStandBlock {
    constructor(config) {
        this.id = config.id;
        this.state = config.state;
        this.tradeEntity = { ...config.tradeEntity, events: config.tradeEntity.events ?? [] }; // Initialize with events or an empty array
        this.radius = config.radius;
        this.maxTraders = config.maxTraders;
        this.spawnEffect = config.spawnEffect;
    }
    static registerBehavior(config) {
        const entity = new MarketStandBlock(config);
        this.register(entity);
    }
    static register(block) {
        MarketStandBlock.blocks.push(block);
    }
    static initialize() {
        world.beforeEvents.worldInitialize.subscribe((event) => {
            event.blockComponentRegistry.registerCustomComponent(`${namespace}:market_stand`, {
                onTick: (event) => {
                    this.handleTick(event);
                },
            });
        });
        system.afterEvents.scriptEventReceive.subscribe((event) => {
            if (event.id === `${namespace}:unlink_market_stand`) {
                this.unlinkEntity(event.sourceEntity);
            }
        });
        world.afterEvents.entityDie.subscribe((event) => {
            this.unlinkEntity(event.deadEntity);
        });
    }
    static handleTick(event) {
        const block = event.block;
        const location = block.location;
        const key = `${location.x},${location.y},${location.z}`;
        const traderCount = world.getDynamicProperty(`${namespace}:market_stand_${key}`);
        if (traderCount === undefined) {
            world.setDynamicProperty(`${namespace}:market_stand_${key}`, 0);
        }
        if (traderCount < 5) {
            this.spawnTradeEntity(block, key, traderCount);
            world.setDynamicProperty(`${namespace}:market_stand_${key}`, traderCount + 1);
        }
        this.ensureMarkerEntity(block);
    }
    static unlinkEntity(entity) {
        if (!entity)
            return;
        try {
            const key = entity.getDynamicProperty(`${namespace}:linked_market_stand_key`);
            if (!key)
                return;
            const traderCount = world.getDynamicProperty(`${namespace}:market_stand_${key}`);
            entity.clearDynamicProperties();
            entity.remove();
            world.setDynamicProperty(`${namespace}:market_stand_${key}`, traderCount - 1);
        }
        catch (error) { }
    }
    static spawnTradeEntity(block, key, traderCount) {
        const blockBehavior = this.getBlockByIdentifier(block.typeId);
        if (!blockBehavior)
            return;
        const tradeEntity = blockBehavior.tradeEntity;
        const radius = blockBehavior.radius;
        const location = block.location;
        const entity = summonEntitiesInRange(location, block.dimension, [
            {
                entity: tradeEntity.id,
                events: tradeEntity.events,
                amount: { min: 1, max: 1 },
                horizontalRadius: radius ?? 30,
                verticalHeight: 5,
                spawnEffects: blockBehavior.spawnEffect,
            },
        ])[0];
        entity.setDynamicProperty(`${namespace}:linked_market_stand_key`, key);
    }
    static ensureMarkerEntity(block) {
        const markerEntityId = `${namespace}:market_stand_marker`;
        const markerExists = block.dimension
            .getEntities({ location: block.location, maxDistance: 1 })
            .some((entity) => entity.typeId === markerEntityId);
        if (!markerExists) {
            // Respawn marker entity if it's missing
            block.dimension.spawnEntity(markerEntityId, block.center());
        }
    }
    static getBlockByIdentifier(identifier) {
        return MarketStandBlock.blocks.find((block) => block.id === identifier);
    }
}
MarketStandBlock.blocks = [];
