package common.block;

import common.entity.Entity;
import common.entity.types.EntityLiving;
import common.init.Blocks;
import common.init.Config;
import common.init.ItemRegistry;
import common.item.Item;
import common.material.Material;
import common.model.Model;
import common.model.ModelProvider;
import common.properties.IProperty;
import common.properties.PropertyInteger;
import common.rng.Random;
import common.util.BlockPos;
import common.util.BoundingBox;
import common.util.Facing;
import common.world.IWorldAccess;
import common.world.State;
import common.world.World;
import common.world.AWorldServer;

public class BlockFarmland extends Block
{
    public static final PropertyInteger MOISTURE = PropertyInteger.create("moisture", 0, 7);

    public BlockFarmland()
    {
        super(Material.ground);
        this.setDefaultState(this.getBaseState().withProperty(MOISTURE, Integer.valueOf(0)));
        this.setTickRandomly();
        this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.9375F, 1.0F);
        this.setLightOpacity(255);
    }

    public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state)
    {
        return new BoundingBox((double)pos.getX(), (double)pos.getY(), (double)pos.getZ(), (double)(pos.getX() + 1), (double)(pos.getY() + 1), (double)(pos.getZ() + 1));
    }

    /**
     * Used to determine ambient occlusion and culling when rebuilding chunks for render
     */
    public boolean isOpaqueCube()
    {
        return false;
    }

    public boolean isFullCube()
    {
        return false;
    }

    public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand)
    {
        int i = ((Integer)state.getValue(MOISTURE)).intValue();

        if (!this.hasWater(worldIn, pos) && !worldIn.isRainingAt(pos.up(), true))
        {
        	if(Config.cropDrying) {
	            if (i > 0)
	            {
	                worldIn.setState(pos, state.withProperty(MOISTURE, Integer.valueOf(i - 1)), 2);
	            }
	            else if (Config.cropDecay && !this.hasCrops(worldIn, pos))
	            {
	                worldIn.setState(pos, Blocks.dirt.getState());
	            }
        	}
        }
        else if (Config.cropSoaking && i < 7)
        {
            worldIn.setState(pos, state.withProperty(MOISTURE, Integer.valueOf(7)), 2);
        }
    }

    /**
     * Block's chance to react to a living entity falling on it.
     */
    public void onFallenUpon(World worldIn, BlockPos pos, Entity entityIn, float fallDistance)
    {
        if (entityIn instanceof EntityLiving)
        {
            if (!worldIn.client && Config.cropTrampling && worldIn.rand.floatv() < fallDistance - 0.5F)
            {
                if (Config.mobGrief)
                	worldIn.setState(pos, Blocks.dirt.getState());
            }

            super.onFallenUpon(worldIn, pos, entityIn, fallDistance);
        }
    }

    private boolean hasCrops(World worldIn, BlockPos pos)
    {
        Block block = worldIn.getState(pos.up()).getBlock();
        return block instanceof BlockCrops || block instanceof BlockStem;
    }

    private boolean hasWater(World worldIn, BlockPos pos)
    {
        for (BlockPos.MutableBlockPos blockpos$mutableblockpos : BlockPos.getAllInBoxMutable(pos.add(-4, 0, -4), pos.add(4, 1, 4)))
        {
            if (worldIn.getState(blockpos$mutableblockpos).getBlock().getMaterial() == Material.water)
            {
                return true;
            }
        }

        return false;
    }

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

        if (worldIn.getState(pos.up()).getBlock().getMaterial().isSolid())
        {
            worldIn.setState(pos, Blocks.dirt.getState());
        }
    }

    public boolean shouldSideBeRendered(IWorldAccess worldIn, BlockPos pos, Facing side)
    {
        switch (side)
        {
            case UP:
                return true;

            case NORTH:
            case SOUTH:
            case WEST:
            case EAST:
                Block block = worldIn.getState(pos).getBlock();
                return !block.isOpaqueCube() && block != Blocks.farmland;

            default:
                return super.shouldSideBeRendered(worldIn, pos, side);
        }
    }

    /**
     * Get the Item that this Block should drop when harvested.
     */
    public Item getItemDropped(State state, Random rand, int fortune)
    {
        return Blocks.dirt.getItemDropped(Blocks.dirt.getState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.DIRT), rand, fortune);
    }

    public Item getItem(World worldIn, BlockPos pos)
    {
        return ItemRegistry.getItemFromBlock(Blocks.dirt);
    }

    /**
     * Convert the given metadata into a BlockState for this Block
     */
    public State getStateFromMeta(int meta)
    {
        return this.getState().withProperty(MOISTURE, Integer.valueOf(meta & 7));
    }

    /**
     * Convert the BlockState into the correct metadata value
     */
    public int getMetaFromState(State state)
    {
        return ((Integer)state.getValue(MOISTURE)).intValue();
    }

    protected IProperty[] getProperties()
    {
        return new IProperty[] {MOISTURE};
    }

    public Model getModel(ModelProvider provider, String name, State state) {
    	return provider.getModel("dirt").add(0, 0, 0, 16, 15, 16).dnswe().u("farmland_" + state.getValue(MOISTURE)).noCull();
    }
}
