import { world, BlockPermutation } from "@minecraft/server"



let isRaining = false
world.afterEvents.weatherChange.subscribe((event) => {
    const { dimension, newWeather, previousWeather } = event

    if ((newWeather == "Rain" || newWeather == "Thunder")) {
        isRaining = true
        // console.warn("RAIn")
    }
    else {
        isRaining = false
        // console.warn("CLEAR")
    }
})


export class RainSensorComponent {
    constructor() {
        this.onTick = this.onTick.bind(this);
    }

    getBlockInDirection(block, direction) {
        switch (direction) {
            case 'north':
                return block.north();
            case 'south':
                return block.south();
            case 'east':
                return block.east();
            case 'west':
                return block.west();
        }
    }

    getOppositeDirection(direction) {
        switch (direction) {
            case 'north':
                return 'south';
            case 'south':
                return 'north';
            case 'east':
                return 'west';
            case 'west':
                return 'east';
        }
    }
    onTick(e) {
        const block = e.block;


        if (isRaining) {
            const directions = ['north', 'south', 'east', 'west'];

            directions.forEach(direction => {
                let adjacentBlock1 = this.getBlockInDirection(block, direction);

                if (adjacentBlock1.permutation.matches("minecraft:unpowered_repeater") && adjacentBlock1.permutation.getState("minecraft:cardinal_direction") === this.getOppositeDirection(direction)) {
                    adjacentBlock1.setPermutation(BlockPermutation.resolve("minecraft:powered_repeater", { 'minecraft:cardinal_direction': this.getOppositeDirection(direction) }));
                }

            });
        }
    }
}