import { Block, Dimension } from "@minecraft/server";
import { blockNeighbors } from "../../library/blockManager";


const waterBlocksList = [
    "minecraft:flowing_water",
    "minecraft:water"
]

/**
 * Evento Tick del componente waterwheelComponent
 * @param {{block: Block, dimension: Dimension}} event 
 */
export const waterwheelEvent = ({block, dimension}) => {
    try {
        if(block.isWaterlogged) {
            const {
                blockNeighborEast,
                blockNeighborWest,
                blockNeighborNorth,
                blockNeighborSouth
            } = blockNeighbors(block);
    
            let permutation = block.permutation;
    
            const direction = block.permutation.getState('minecraft:cardinal_direction');
    
            switch (direction) {
                case 'north':
                case 'south':
                    if(isWaterPresent(blockNeighborNorth, blockNeighborSouth)) {
                        permutation = permutation.withState('nps_ec:animation', !permutation.getState('nps_ec:animation'));
                        permutation = permutation.withState('nps_ec:power', 1);
                    } else{
                        permutation = permutation.withState('nps_ec:animation', false);
                        permutation = permutation.withState('nps_ec:power', 0);
                    }
                    break;
                case 'west':
                case 'east':
                    if(isWaterPresent(blockNeighborEast, blockNeighborWest)) {
                        permutation = permutation.withState('nps_ec:animation', !permutation.getState('nps_ec:animation'));
                        permutation = permutation.withState('nps_ec:power', 1);
                    } else {
                        permutation = permutation.withState('nps_ec:animation', false);
                        permutation = permutation.withState('nps_ec:power', 0);
                    }
                    break;
            }
    
            block.setPermutation(permutation);
        }
    } catch { }
}


const isWaterPresent = (block1, block2) => 
    waterBlocksList.includes(block1.typeId) && waterBlocksList.includes(block2.typeId);