package common.entity.item;

import common.block.Material;
import common.color.TextColor;
import common.entity.DamageSource;
import common.entity.Entity;
import common.entity.EntityType;
import common.entity.npc.EntityNPC;
import common.entity.types.EntityLiving;
import common.init.ItemRegistry;
import common.init.Items;
import common.init.SoundEvent;
import common.item.Item;
import common.item.ItemStack;
import common.log.Log;
import common.model.ParticleType;
import common.tags.TagObject;
import common.util.BlockPos;
import common.util.ExtMath;
import common.util.PortalType;
import common.vars.Vars;
import common.world.World;
import common.world.AWorldServer;

public class EntityItem extends Entity
{
    /**
     * The age of this EntityItem (used to animate it up and down as well as expire it)
     */
    private int age;
    private int delayBeforeCanPickup;

    /** The health of this EntityItem. (For example, damage for tools) */
    private int health;
//    private String thrower;
//    private String owner;

    /** The EntityItem's random initial float height. */
    public float hoverStart;

    public EntityItem(World worldIn, double x, double y, double z)
    {
        super(worldIn);
        this.health = 5;
        this.hoverStart = (float)(Math.random() * Math.PI * 2.0D);
        this.setSize(0.25F, 0.25F);
        this.setPosition(x, y, z);
        this.rotYaw = (float)(Math.random() * 360.0D);
        this.motionX = (double)((float)(Math.random() * 0.20000000298023224D - 0.10000000149011612D));
        this.motionY = 0.20000000298023224D;
        this.motionZ = (double)((float)(Math.random() * 0.20000000298023224D - 0.10000000149011612D));
    }

    public EntityItem(World worldIn, double x, double y, double z, ItemStack stack)
    {
        this(worldIn, x, y, z);
        this.setEntityItemStack(stack);
    }

//    public EntityItem(World worldIn, double x, double y, double z, int data)
//    {
//        this(worldIn, x, y, z);
//    }

    public void fall(float distance, float damageMultiplier)
    {
        if(!this.worldObj.client && Vars.itemFallDamage && distance >= 1.0f && this.getEntityItem().getItem().isFragile()) {
//        	for(int z = 0; z < 8; z++) {
        	((AWorldServer)this.worldObj).spawnParticle(ParticleType.ITEM_CRACK, this.posX, this.posY, this.posZ, 
        			8, this.rand.gaussian() * 0.15D, this.rand.doublev() * 0.2D, this.rand.gaussian() * 0.15D, 0.1f,
        			ItemRegistry.getIdFromItem(this.getEntityItem().getItem()));
//        	}
        	this.worldObj.playAuxSFX(1023, this.getPosition(), 0);
        	this.setDead();
        }
    }

    /**
     * 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;
    }

    public EntityItem(World worldIn)
    {
        super(worldIn);
        this.health = 5;
        this.hoverStart = (float)(Math.random() * Math.PI * 2.0D);
        this.setSize(0.25F, 0.25F);
        this.setEntityItemStack(new ItemStack((Item)null, 0));
    }

    protected void entityInit()
    {
        this.getDataWatcher().addObjectByDataType(10, 5);
    }

    /**
     * Called to update the entity's position/logic.
     */
    public void onUpdate()
    {
        if (this.getEntityItem() == null)
        {
            this.setDead();
        }
        else
        {
            super.onUpdate();

            if (this.delayBeforeCanPickup > 0 && this.delayBeforeCanPickup != 32767)
            {
                --this.delayBeforeCanPickup;
            }

            this.prevX = this.posX;
            this.prevY = this.posY;
            this.prevZ = this.posZ;
            this.motionY -= 0.03999999910593033D;
            this.noClip = this.pushOutOfBlocks(this.posX, (this.getEntityBoundingBox().minY + this.getEntityBoundingBox().maxY) / 2.0D, this.posZ);
            this.moveEntity(this.motionX, this.motionY, this.motionZ);
            boolean flag = (int)this.prevX != (int)this.posX || (int)this.prevY != (int)this.posY || (int)this.prevZ != (int)this.posZ;

            if (flag || this.ticksExisted % 25 == 0)
            {
                if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() == Material.LAVA)
                {
                    this.motionY = 0.20000000298023224D;
                    this.motionX = (double)((this.rand.floatv() - this.rand.floatv()) * 0.2F);
                    this.motionZ = (double)((this.rand.floatv() - this.rand.floatv()) * 0.2F);
                    this.playSound(SoundEvent.FIZZ, 0.4F);
                }

                if (!this.worldObj.client)
                {
                    this.searchForOtherItemsNearby();
                }
            }
            
            if(!this.worldObj.client && this.ticksExisted % 5 == 0) {
            	ItemStack stack = this.getEntityItem();
            	float rad = stack.getItem().getRadiation(stack);
            	if(rad > 0.0f)
            		this.affectEntities(rad * 0.25f);
            }

            float f = 0.98F;

            if (this.onGround)
            {
                f = this.worldObj.getState(new BlockPos(ExtMath.floord(this.posX), ExtMath.floord(this.getEntityBoundingBox().minY) - 1, ExtMath.floord(this.posZ))).getBlock().slipperiness * 0.98F;
            }

            this.motionX *= (double)f;
            this.motionY *= 0.9800000190734863D;
            this.motionZ *= (double)f;

            if (this.onGround)
            {
                this.motionY *= -0.5D;
            }

            if (this.age != -32768)
            {
                ++this.age;
            }

            this.handleWaterMovement();

            if (!this.worldObj.client && this.age >= 6000)
            {
                this.setDead();
            }
        }
    }

    /**
     * Looks for other itemstacks nearby and tries to stack them together
     */
    private void searchForOtherItemsNearby()
    {
        for (EntityItem entityitem : this.worldObj.getEntitiesWithinAABB(EntityItem.class, this.getEntityBoundingBox().expand(0.5D, 0.0D, 0.5D)))
        {
            this.combineItems(entityitem);
        }
    }

    private void affectEntities(float rad)
    {
    	float r = ExtMath.clampf(rad * 2.0f, 0.0f, 25.0f);
        for (EntityLiving entity : this.worldObj.getEntitiesWithinAABB(EntityLiving.class, this.getEntityBoundingBox().expand(r, r, r)))
        {
        	float effect = rad * 2.0f * (r - (float)this.getDistanceToEntity(entity)) / r;
        	if(effect > 0.0f)
        		entity.addRadiation(effect);
        }
    }

    /**
     * Tries to merge this item with the item passed as the parameter. Returns true if successful. Either this item or
     * the other item will  be removed from the world.
     */
    private boolean combineItems(EntityItem other)
    {
        if (other == this)
        {
            return false;
        }
        else if (other.isEntityAlive() && this.isEntityAlive())
        {
            ItemStack itemstack = this.getEntityItem();
            ItemStack itemstack1 = other.getEntityItem();

            if (this.delayBeforeCanPickup != 32767 && other.delayBeforeCanPickup != 32767)
            {
                if (this.age != -32768 && other.age != -32768)
                {
                    if (itemstack1.getItem() != itemstack.getItem())
                    {
                        return false;
                    }
                    else if (itemstack1.hasTagCompound() ^ itemstack.hasTagCompound())
                    {
                        return false;
                    }
                    else if (itemstack1.hasTagCompound() && !itemstack1.getTagCompound().equals(itemstack.getTagCompound()))
                    {
                        return false;
                    }
                    else if (itemstack1.getItem() == null)
                    {
                        return false;
                    }
                    else if (itemstack1.size < itemstack.size)
                    {
                        return other.combineItems(this);
                    }
                    else if (itemstack1.size + itemstack.size > itemstack1.getMaxStackSize())
                    {
                        return false;
                    }
                    else
                    {
                        itemstack1.size += itemstack.size;
                        other.delayBeforeCanPickup = Math.max(other.delayBeforeCanPickup, this.delayBeforeCanPickup);
                        other.age = Math.min(other.age, this.age);
                        other.setEntityItemStack(itemstack1);
                        this.setDead();
                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

//    /**
//     * sets the age of the item so that it'll despawn one minute after it has been dropped (instead of five). Used when
//     * items are dropped from players in creative mode
//     */
//    public void setAgeToCreativeDespawnTime()
//    {
//        this.age = 4800;
//    }

    /**
     * Returns if this entity is in water and will end up adding the waters velocity to the entity
     */
    public boolean handleWaterMovement()
    {
        if (this.worldObj.handleLiquidAcceleration(this.getEntityBoundingBox(), this))
        {
            if (!this.inLiquid && !this.firstUpdate)
            {
                this.onEnterLiquid();
            }

            this.inLiquid = true;
        }
        else
        {
            this.inLiquid = false;
        }

        return this.inLiquid;
    }

    /**
     * Will deal the specified amount of damage to the entity if the entity isn't immune to fire damage. Args:
     * amountDamage
     */
    protected void dealFireDamage(int amount)
    {
    	if(Vars.itemBurn)
    		this.attackEntityFrom(DamageSource.inFire, amount);
    }

    /**
     * Called when the entity is attacked.
     */
    public boolean attackEntityFrom(DamageSource source, int amount)
    {
//        if (this.isEntityInvulnerable(source))
//        {
//            return false;
//        }
////        else if (this.getEntityItem() != null && this.getEntityItem().getItem() == Items.nether_star && source.isExplosion())
////        {
////            return false;
////        }
//        else
//        {
        this.setBeenAttacked();
        this.health = this.health - (int)amount;

        if (this.health <= 0)
        {
            this.setDead();
        }

        return false;
//        }
    }

    /**
     * (abstract) Protected helper method to write subclass entity data to NBT.
     */
    public void writeEntity(TagObject tagCompound)
    {
        tagCompound.setShort("Health", (short)((byte)this.health));
        tagCompound.setShort("Age", (short)this.age);
        tagCompound.setShort("PickupDelay", (short)this.delayBeforeCanPickup);

//        if (this.getThrower() != null)
//        {
//            tagCompound.setString("Thrower", this.thrower);
//        }
//
//        if (this.getOwner() != null)
//        {
//            tagCompound.setString("Owner", this.owner);
//        }

        if (this.getEntityItem() != null)
        {
            tagCompound.setObject("Item", this.getEntityItem().writeTags(new TagObject()));
        }
    }

    /**
     * (abstract) Protected helper method to read subclass entity data from NBT.
     */
    public void readEntity(TagObject tagCompund)
    {
        this.health = tagCompund.getShort("Health") & 255;
        this.age = tagCompund.getShort("Age");

        this.delayBeforeCanPickup = tagCompund.getShort("PickupDelay");

//        if (tagCompund.hasKey("Owner"))
//        {
//            this.owner = tagCompund.getString("Owner");
//        }
//
//        if (tagCompund.hasKey("Thrower"))
//        {
//            this.thrower = tagCompund.getString("Thrower");
//        }

        TagObject nbttagcompound = tagCompund.getObject("Item");
        this.setEntityItemStack(ItemStack.readFromTag(nbttagcompound));

        if (this.getEntityItem() == null)
        {
            this.setDead();
        }
    }

    /**
     * Called by a player entity when they collide with an entity
     */
    public void onCollideWithPlayer(EntityNPC entityIn)
    {
        if (!this.worldObj.client)
        {
            ItemStack itemstack = this.getEntityItem();
            int i = itemstack.size;

            if (this.delayBeforeCanPickup == 0 // && (this.owner == null || 6000 - this.age <= 200 || this.owner.equals(entityIn.getUser())) 
            		&& entityIn.inventory.addItemStackToInventory(itemstack))
            {
//                if (itemstack.getItem() == Items.log)
//                {
//                    entityIn.triggerAchievement(AchievementList.mineWood);
//                }
//
//                if (itemstack.getItem() == Items.log2)
//                {
//                    entityIn.triggerAchievement(AchievementList.mineWood);
//                }
//
//                if (itemstack.getItem() == Items.leather)
//                {
//                    entityIn.triggerAchievement(AchievementList.killCow);
//                }
//
//                if (itemstack.getItem() == Items.diamond)
//                {
//                    entityIn.triggerAchievement(AchievementList.diamonds);
//                }
//
//                if (itemstack.getItem() == Items.blaze_rod)
//                {
//                    entityIn.triggerAchievement(AchievementList.blazeRod);
//                }
//
//                if (itemstack.getItem() == Items.diamond && this.getThrower() != null)
//                {
//                    EntityNPC entityplayer = this.worldObj.getPlayer(this.getThrower());
//
//                    if (entityplayer != null && entityplayer != entityIn)
//                    {
//                        entityplayer.triggerAchievement(AchievementList.diamondsToYou);
//                    }
//                }

//                if (!this.isSilent())
//                {
                this.worldObj.playSoundAtEntity(entityIn, SoundEvent.POP, 0.2F);
//                }

                entityIn.onItemPickup(this, i);

                if (itemstack.size <= 0)
                {
                    this.setDead();
                }
            }
        }
    }

    /**
     * Get the name of this object. For players this returns their username
     */
    public String getTypeName()
    {
        if(this.hasCustomName())
        	return this.getCustomNameTag();
        String comp = super.getTypeName();
        comp += " (" + this.getEntityItem().size + " * " +
        		ItemRegistry.getNameFromItem(this.getEntityItem().getItem()) + ")";
        return comp;
    }

    /**
     * If returns false, the item will not inflict any damage against entities.
     */
    public boolean canAttackWithItem()
    {
        return false;
    }

    /**
     * Teleports the entity to another dimension. Params: Dimension number to teleport to
     */
    public Entity travelToDimension(int dimensionId, BlockPos pos, float yaw, float pitch, PortalType portal)
    {
        Entity entity = super.travelToDimension(dimensionId, pos, yaw, pitch, portal);

        if (!this.worldObj.client)
        {
            this.searchForOtherItemsNearby();
        }
        
        return entity;
    }

    /**
     * Returns the ItemStack corresponding to the Entity (Note: if no item exists, will log an error but still return an
     * ItemStack containing Block.stone)
     */
    public ItemStack getEntityItem()
    {
        ItemStack itemstack = this.getDataWatcher().getWatchableObjectItemStack(10);

        if (itemstack == null)
        {
            if (this.worldObj != null)
            {
            	Log.TICK.warn("Gegenstand-Objekt " + this.getId() + " hat kein Item?!");
            }

            return new ItemStack(Items.stone);
        }
        else
        {
            return itemstack;
        }
    }

    /**
     * Sets the ItemStack for this entity
     */
    public void setEntityItemStack(ItemStack stack)
    {
        this.getDataWatcher().updateObject(10, stack);
        this.getDataWatcher().setObjectWatched(10);
    }

//    public String getOwner()
//    {
//        return this.owner;
//    }
//
//    public void setOwner(String owner)
//    {
//        this.owner = owner;
//    }

//    public String getThrower()
//    {
//        return this.thrower;
//    }
//
//    public void setThrower(String thrower)
//    {
//        this.thrower = thrower;
//    }

    public int getAge()
    {
        return this.age;
    }

    public void setDefaultPickupDelay()
    {
        this.delayBeforeCanPickup = 10;
    }

//    public void setNoPickupDelay()
//    {
//        this.delayBeforeCanPickup = 0;
//    }

//    public void setInfinitePickupDelay()
//    {
//        this.delayBeforeCanPickup = 32767;
//    }

    public void setPickupDelay(int ticks)
    {
        this.delayBeforeCanPickup = ticks;
    }

    public boolean cannotPickup()
    {
        return this.delayBeforeCanPickup > 0;
    }

    public void setNoDespawn()
    {
        this.age = -6000;
    }

//    public void setNoPickup()
//    {
//        this.setInfinitePickupDelay();
//        this.age = 5999;
//    }
    
    public int getTrackingRange() {
    	return 64;
    }
    
    public int getUpdateFrequency() {
    	return 20;
    }
    
    public boolean isSendingVeloUpdates() {
    	return true;
    }
	
//	public int getPacketData() {
//		return 1;
//	}
	
	public boolean hasSpawnVelocity() {
		return true;
	}
    
    public boolean isMagnetic() {
    	return this.getEntityItem().getItem().isMagnetic();
    }
    
    public String getDisplayName()
    {
    	ItemStack stack = this.getEntityItem();
    	if(stack.size <= 1)
    		return null;
    	return TextColor.DGREEN + "" + stack.size;
    }
    
    public EntityType getType() {
    	return EntityType.OBJECT;
    }
}
