package common.block;

import common.entity.item.EntityFalling;
import common.init.Blocks;
import common.init.Config;
import common.item.CheatTab;
import common.material.Material;
import common.rng.Random;
import common.util.BlockPos;
import common.world.State;
import common.world.World;
import common.world.AWorldServer;

public class BlockFalling extends Block
{
    public static boolean fallInstantly;

    public BlockFalling()
    {
        super(Material.sand);
        this.setTab(CheatTab.tabNature);
    }

    public BlockFalling(Material materialIn)
    {
        super(materialIn);
    }

    public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state)
    {
        worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn, pos));
    }

    /**
     * Called when a neighboring block changes.
     */
    public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock)
    {
        worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn, pos));
    }

    public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand)
    {
        if(/* !worldIn.client && */ Config.blockGravity)
            this.checkFallable(worldIn, pos);
    }

    private void checkFallable(World worldIn, BlockPos pos)
    {
        if (canFallInto(worldIn, pos.down()) && pos.getY() >= 0)
        {
            int i = 32;

            if (!fallInstantly && worldIn.isAreaLoaded(pos.add(-i, -i, -i), pos.add(i, i, i)))
            {
                if (!worldIn.client)
                {
                    EntityFalling entityfallingblock = new EntityFalling(worldIn, (double)pos.getX() + 0.5D, (double)pos.getY(), (double)pos.getZ() + 0.5D, worldIn.getState(pos));
                    this.onStartFalling(entityfallingblock);
                    worldIn.spawnEntityInWorld(entityfallingblock);
                }
            }
            else
            {
                worldIn.setBlockToAir(pos);
                BlockPos blockpos;

                for (blockpos = pos.down(); canFallInto(worldIn, blockpos) && blockpos.getY() > 0; blockpos = blockpos.down())
                {
                    ;
                }

                if (blockpos.getY() > 0)
                {
                    worldIn.setState(blockpos.up(), this.getState());
                }
            }
        }
    }

    protected void onStartFalling(EntityFalling fallingEntity)
    {
    }

    /**
     * How many world ticks before ticking
     */
    public int tickRate(World worldIn, BlockPos pos)
    {
        return 2;
    }

    public static boolean canFallInto(World worldIn, BlockPos pos)
    {
        Block block = worldIn.getState(pos).getBlock();
        Material material = block.material;
        return block == Blocks.fire || material == Material.air || material.isLiquid();
    }

    public void onEndFalling(World worldIn, BlockPos pos)
    {
    }
}
