package common.entity.item;

import java.util.List;

import common.block.Block;
import common.block.BlockAnvil;
import common.block.BlockFalling;
import common.block.ITileEntityProvider;
import common.collect.Lists;
import common.entity.DamageSource;
import common.entity.Entity;
import common.entity.EntityType;
import common.entity.types.IObjectData;
import common.init.BlockRegistry;
import common.init.Blocks;
import common.init.Config;
import common.item.ItemStack;
import common.material.Material;
import common.nbt.NBTBase;
import common.nbt.NBTTagCompound;
import common.tileentity.TileEntity;
import common.util.BlockPos;
import common.util.ExtMath;
import common.util.Facing;
import common.world.State;
import common.world.World;

public class EntityFalling extends Entity implements IObjectData
{
    private State fallTile;
    public int fallTime;
    public boolean shouldDropItem = true;
    private boolean canSetAsBlock;
    private boolean hurtEntities;
    private int fallHurtMax = 40;
    private float fallHurtAmount = 2.0F;
    public NBTTagCompound tileEntityData;

    public EntityFalling(World worldIn)
    {
        super(worldIn);
    }

    public EntityFalling(World worldIn, double x, double y, double z, State fallingBlockState)
    {
        super(worldIn);
        this.fallTile = fallingBlockState;
        this.preventSpawning = true;
        this.setSize(0.98F, 0.98F);
        this.setPosition(x, y, z);
        this.motionX = 0.0D;
        this.motionY = 0.0D;
        this.motionZ = 0.0D;
        this.prevX = x;
        this.prevY = y;
        this.prevZ = z;
    }

    public EntityFalling(World worldIn, double x, double y, double z, int data)
    {
    	this(worldIn, x, y, z, BlockRegistry.getStateById(data & 65535));
    }

    /**
     * returns if this entity triggers Block.onEntityWalking on the blocks they walk on. used for spiders and wolves to
     * prevent them from trampling crops
     */
    protected boolean canTriggerWalking()
    {
        return false;
    }

    protected void entityInit()
    {
    }

    /**
     * Returns true if other Entities should be prevented from moving through this Entity.
     */
    public boolean canBeCollidedWith()
    {
        return !this.dead;
    }

    /**
     * Called to update the entity's position/logic.
     */
    public void onUpdate()
    {
        Block block = this.fallTile.getBlock();

        if (block.getMaterial() == Material.air)
        {
            this.setDead();
        }
        else
        {
            this.prevX = this.posX;
            this.prevY = this.posY;
            this.prevZ = this.posZ;

            if (this.fallTime++ == 0)
            {
                BlockPos blockpos = new BlockPos(this);

                if (this.worldObj.getState(blockpos).getBlock() == block)
                {
                    this.worldObj.setBlockToAir(blockpos);
                }
                else if (!this.worldObj.client)
                {
                    this.setDead();
                    return;
                }
            }

            this.motionY -= 0.03999999910593033D;
            this.moveEntity(this.motionX, this.motionY, this.motionZ);
            this.motionX *= 0.9800000190734863D;
            this.motionY *= 0.9800000190734863D;
            this.motionZ *= 0.9800000190734863D;

            if (!this.worldObj.client)
            {
                BlockPos blockpos1 = new BlockPos(this);

                if (this.onGround)
                {
                    this.motionX *= 0.699999988079071D;
                    this.motionZ *= 0.699999988079071D;
                    this.motionY *= -0.5D;

                    if (this.worldObj.getState(blockpos1).getBlock() != Blocks.piston_extension)
                    {
                        this.setDead();

                        if (!this.canSetAsBlock)
                        {
                            if (this.worldObj.canBlockBePlaced(block, blockpos1, true, Facing.UP, (Entity)null, (ItemStack)null) && !BlockFalling.canFallInto(this.worldObj, blockpos1.down()) && this.worldObj.setState(blockpos1, this.fallTile, 3))
                            {
                                if (block instanceof BlockFalling)
                                {
                                    ((BlockFalling)block).onEndFalling(this.worldObj, blockpos1);
                                }

                                if (this.tileEntityData != null && block instanceof ITileEntityProvider)
                                {
                                    TileEntity tileentity = this.worldObj.getTileEntity(blockpos1);

                                    if (tileentity != null)
                                    {
                                        NBTTagCompound nbttagcompound = new NBTTagCompound();
                                        tileentity.writeToNBT(nbttagcompound);

                                        for (String s : this.tileEntityData.getKeySet())
                                        {
                                            NBTBase nbtbase = this.tileEntityData.getTag(s);

                                            if (!s.equals("x") && !s.equals("y") && !s.equals("z"))
                                            {
                                                nbttagcompound.setTag(s, nbtbase.copy());
                                            }
                                        }

                                        tileentity.readFromNBT(nbttagcompound);
                                        tileentity.markDirty();
                                    }
                                }
                            }
                            else if (this.shouldDropItem && Config.objectDrop)
                            {
                                this.entityDropItem(new ItemStack(block, 1, block.damageDropped(this.fallTile)), 0.0F);
                            }
                        }
                    }
                }
                else if (this.fallTime > 100 && !this.worldObj.client && (blockpos1.getY() < 1 || blockpos1.getY() > 512) || this.fallTime > 600)
                {
                    if (this.shouldDropItem && Config.objectDrop)
                    {
                        this.entityDropItem(new ItemStack(block, 1, block.damageDropped(this.fallTile)), 0.0F);
                    }

                    this.setDead();
                }
            }
        }
    }

    public void fall(float distance, float damageMultiplier)
    {
        Block block = this.fallTile.getBlock();

        if (this.hurtEntities)
        {
            int i = ExtMath.ceilf(distance - 1.0F);

            if (i > 0)
            {
                List<Entity> list = Lists.newArrayList(this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox()));
                boolean flag = block == Blocks.anvil;
                DamageSource damagesource = flag ? DamageSource.anvil : DamageSource.fallingBlock;

                if(this.worldObj.client || (flag ? Config.damageAcme : Config.damageSquish)) {
	                for (Entity entity : list)
	                {
	                    entity.attackEntityFrom(damagesource, Math.min(ExtMath.floorf((float)i * this.fallHurtAmount), this.fallHurtMax));
	                }
                }

                if (flag && (this.worldObj.client || Config.anvilFallDecay) && (double)this.rand.floatv() < 0.05000000074505806D + (double)i * 0.05D)
                {
                    int j = ((Integer)this.fallTile.getValue(BlockAnvil.DAMAGE)).intValue();
                    ++j;

                    if (j > 2)
                    {
                        this.canSetAsBlock = true;
                    }
                    else
                    {
                        this.fallTile = this.fallTile.withProperty(BlockAnvil.DAMAGE, Integer.valueOf(j));
                    }
                }
            }
        }
    }

    /**
     * (abstract) Protected helper method to write subclass entity data to NBT.
     */
    protected void writeEntityToNBT(NBTTagCompound tagCompound)
    {
        Block block = this.fallTile != null ? this.fallTile.getBlock() : Blocks.air;
        String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(block);
        tagCompound.setString("Block", resourcelocation == null ? "" : resourcelocation.toString());
        tagCompound.setByte("Data", (byte)block.getMetaFromState(this.fallTile));
        tagCompound.setByte("Time", (byte)this.fallTime);
        tagCompound.setBoolean("DropItem", this.shouldDropItem);
        tagCompound.setBoolean("HurtEntities", this.hurtEntities);
        tagCompound.setFloat("FallHurtAmount", this.fallHurtAmount);
        tagCompound.setInteger("FallHurtMax", this.fallHurtMax);

        if (this.tileEntityData != null)
        {
            tagCompound.setTag("TileEntityData", this.tileEntityData);
        }
    }

    /**
     * (abstract) Protected helper method to read subclass entity data from NBT.
     */
    protected void readEntityFromNBT(NBTTagCompound tagCompund)
    {
        int i = tagCompund.getByte("Data") & 255;

        if (tagCompund.hasKey("Block", 8))
        {
            this.fallTile = BlockRegistry.getByIdFallback(tagCompund.getString("Block")).getStateFromMeta(i);
        }
        else if (tagCompund.hasKey("TileID", 99))
        {
            this.fallTile = BlockRegistry.getBlockById(tagCompund.getInteger("TileID")).getStateFromMeta(i);
        }
        else
        {
            this.fallTile = BlockRegistry.getBlockById(tagCompund.getByte("Tile") & 255).getStateFromMeta(i);
        }

        this.fallTime = tagCompund.getByte("Time") & 255;
        Block block = this.fallTile.getBlock();

        if (tagCompund.hasKey("HurtEntities", 99))
        {
            this.hurtEntities = tagCompund.getBoolean("HurtEntities");
            this.fallHurtAmount = tagCompund.getFloat("FallHurtAmount");
            this.fallHurtMax = tagCompund.getInteger("FallHurtMax");
        }
        else if (block == Blocks.anvil)
        {
            this.hurtEntities = true;
        }

        if (tagCompund.hasKey("DropItem", 99))
        {
            this.shouldDropItem = tagCompund.getBoolean("DropItem");
        }

        if (tagCompund.hasKey("TileEntityData", 10))
        {
            this.tileEntityData = tagCompund.getCompoundTag("TileEntityData");
        }

        if (block == null || block.getMaterial() == Material.air)
        {
            this.fallTile = Blocks.sand.getState();
        }
    }

    public World getWorldObj()
    {
        return this.worldObj;
    }

    public void setHurtEntities(boolean p_145806_1_)
    {
        this.hurtEntities = p_145806_1_;
    }

    /**
     * Return whether this entity should be rendered as on fire.
     */
    public boolean canRenderOnFire()
    {
        return false;
    }

    public State getBlock()
    {
        return this.fallTile;
    }
    
    public int getTrackingRange() {
    	return 160;
    }
    
    public int getUpdateFrequency() {
    	return 20;
    }
    
    public boolean isSendingVeloUpdates() {
    	return true;
    }
	
	public int getPacketData() {
		return BlockRegistry.getStateId(this.fallTile);
	}
	
//	public boolean hasSpawnVelocity() {
//		return false;
//	}
    
    public EntityType getType() {
    	return EntityType.OBJECT;
    }
}
