import { BlockPermutation } from '@minecraft/server';
export default class BlockTransformation {
    constructor(blockName, options) {
        this.permutation = blockName ? BlockPermutation.resolve(blockName, options?.states) : undefined;
        this.options = options;
    }
    testConditions(block) {
        const conditions = this.options?.conditions;
        if (!conditions)
            return true;
        for (const [k, v] of Object.entries(conditions)) {
            if (block.permutation.getState(k) !== v) {
                return false;
            }
        }
        return true;
    }
    getNewState(state, value) {
        const stateMapFunc = this.options?.mapStates?.[state] || state;
        if (typeof stateMapFunc === 'string') {
            return { state: stateMapFunc, value };
        }
        return stateMapFunc(value);
    }
    transform(block) {
        if (!this.testConditions(block))
            return this.options?.setBiome;
        this.options?.beforeConvert?.(block);
        const oldPermutation = block.permutation;
        if (!this.permutation || (this.options?.destroyChance ?? 0) > Math.random()) {
            block.setType('minecraft:air');
        }
        else {
            let { permutation } = this;
            Object.entries(block.permutation.getAllStates()).forEach(([k, v]) => {
                const newState = this.getNewState(k, v);
                try {
                    permutation = permutation.withState(newState.state, newState.value);
                }
                catch {
                    // Throws if state does not exist. Ignore and continue.
                }
            });
            block.setPermutation(permutation);
        }
        this.options?.afterConvert?.(block, oldPermutation);
        return this.options?.setBiome;
    }
}
