package common.entity.projectile;

import java.util.List;

import common.block.Block;
import common.entity.DamageSource;
import common.entity.Entity;
import common.entity.EntityType;
import common.entity.types.EntityLiving;
import common.init.BlockRegistry;
import common.model.ParticleType;
import common.nbt.NBTTagCompound;
import common.nbt.NBTTagList;
import common.util.BlockPos;
import common.util.BoundingBox;
import common.util.ExtMath;
import common.util.HitPosition;
import common.util.Vec3;
import common.world.World;

public abstract class EntityProjectile extends Entity
{
    private int xTile = -1;
    private int yTile = -1;
    private int zTile = -1;
    private Block inTile;
    private boolean inGround;
    public EntityLiving shootingEntity;
    private int ticksAlive;
    private int ticksInAir;
    public double accelerationX;
    public double accelerationY;
    public double accelerationZ;
	private int age;

    public EntityProjectile(World worldIn)
    {
        super(worldIn);
        this.setSize(1.0F, 1.0F);
    }

    protected void entityInit()
    {
    }

    /**
     * Checks if the entity is in range to render by using the past in distance and comparing it to its average edge
     * length * 64 * renderDistanceWeight Args: distance
     */
    public boolean isInRangeToRenderDist(double distance)
    {
        double d0 = this.getEntityBoundingBox().getAverageEdgeLength() * 4.0D;

        if (Double.isNaN(d0))
        {
            d0 = 4.0D;
        }

        d0 = d0 * 64.0D;
        return distance < d0 * d0;
    }

    public EntityProjectile(World worldIn, double x, double y, double z)
    {
        super(worldIn);
        this.setSize(1.0F, 1.0F);
        this.setLocationAndAngles(x, y, z, this.rotYaw, this.rotPitch);
        this.setPosition(x, y, z);
    }

    public EntityProjectile(World worldIn, EntityLiving shooter, double accelX, double accelY, double accelZ, double random, double velo)
    {
        super(worldIn);
        this.shootingEntity = shooter;
        this.setSize(1.0F, 1.0F);
        this.setLocationAndAngles(shooter.posX, shooter.posY, shooter.posZ, shooter.rotYaw, shooter.rotPitch);
        this.setPosition(this.posX, this.posY, this.posZ);
        this.motionX = this.motionY = this.motionZ = 0.0D;
        accelX = accelX + this.rand.gaussian() * random;
        accelY = accelY + this.rand.gaussian() * random;
        accelZ = accelZ + this.rand.gaussian() * random;
        double d0 = (double)ExtMath.sqrtd(accelX * accelX + accelY * accelY + accelZ * accelZ);
        this.accelerationX = (accelX / d0 * 0.1D) * velo;
        this.accelerationY = (accelY / d0 * 0.1D) * velo;
        this.accelerationZ = (accelZ / d0 * 0.1D) * velo;
    }
    
    public void setAcceleration(double accelX, double accelY, double accelZ) {
    	double d0 = (double)ExtMath.sqrtd(accelX * accelX + accelY * accelY + accelZ * accelZ);
        this.accelerationX = accelX / d0 * 0.1D;
        this.accelerationY = accelY / d0 * 0.1D;
        this.accelerationZ = accelZ / d0 * 0.1D;
    }
    
    public Vec3 getAcceleration() {
    	return new Vec3(this.accelerationX, this.accelerationY, this.accelerationZ);
    }

    /**
     * Called to update the entity's position/logic.
     */
    public void onUpdate()
    {
        if (this.worldObj.client || (this.shootingEntity == null || !this.shootingEntity.dead) && this.worldObj.isBlockLoaded(new BlockPos(this)))
        {
            super.onUpdate();
            this.setFire(1);

            if (this.inGround)
            {
                if (this.worldObj.getState(new BlockPos(this.xTile, this.yTile, this.zTile)).getBlock() == this.inTile)
                {
                    ++this.ticksAlive;

                    if (this.ticksAlive == 600)
                    {
                        this.setDead();
                    }

                    return;
                }

                this.inGround = false;
                this.motionX *= (double)(this.rand.floatv() * 0.2F);
                this.motionY *= (double)(this.rand.floatv() * 0.2F);
                this.motionZ *= (double)(this.rand.floatv() * 0.2F);
                this.ticksAlive = 0;
                this.ticksInAir = 0;
            }
            else
            {
                ++this.ticksInAir;
            }

            Vec3 vec3 = new Vec3(this.posX, this.posY, this.posZ);
            Vec3 vec31 = new Vec3(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
            HitPosition movingobjectposition = this.worldObj.rayTraceBlocks(vec3, vec31);
            vec3 = new Vec3(this.posX, this.posY, this.posZ);
            vec31 = new Vec3(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);

            if (movingobjectposition != null)
            {
                vec31 = new Vec3(movingobjectposition.vec.xCoord, movingobjectposition.vec.yCoord, movingobjectposition.vec.zCoord);
            }

            Entity entity = null;
            List<Entity> list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox().addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D));
            double d0 = 0.0D;

            for (int i = 0; i < list.size(); ++i)
            {
                Entity entity1 = (Entity)list.get(i);

                if (entity1.canBeCollidedWith() && (!entity1.isEntityEqual(this.shootingEntity) || this.ticksInAir >= 25))
                {
                    float f = 0.3F;
                    BoundingBox axisalignedbb = entity1.getEntityBoundingBox().expand((double)f, (double)f, (double)f);
                    HitPosition movingobjectposition1 = axisalignedbb.calculateIntercept(vec3, vec31);

                    if (movingobjectposition1 != null)
                    {
                        double d1 = vec3.squareDistanceTo(movingobjectposition1.vec);

                        if (d1 < d0 || d0 == 0.0D)
                        {
                            entity = entity1;
                            d0 = d1;
                        }
                    }
                }
            }

            if (entity != null)
            {
                movingobjectposition = new HitPosition(entity);
            }

            if (movingobjectposition != null)
            {
                this.onImpact(movingobjectposition);
            }

            this.posX += this.motionX;
            this.posY += this.motionY;
            this.posZ += this.motionZ;
            float f1 = ExtMath.sqrtd(this.motionX * this.motionX + this.motionZ * this.motionZ);
            this.rotYaw = (float)(ExtMath.atan2(this.motionZ, this.motionX) * 180.0D / Math.PI) + 90.0F;

            for (this.rotPitch = (float)(ExtMath.atan2((double)f1, this.motionY) * 180.0D / Math.PI) - 90.0F; this.rotPitch - this.prevPitch < -180.0F; this.prevPitch -= 360.0F)
            {
                ;
            }

            while (this.rotPitch - this.prevPitch >= 180.0F)
            {
                this.prevPitch += 360.0F;
            }

            while (this.rotYaw - this.prevYaw < -180.0F)
            {
                this.prevYaw -= 360.0F;
            }

            while (this.rotYaw - this.prevYaw >= 180.0F)
            {
                this.prevYaw += 360.0F;
            }

            this.rotPitch = this.prevPitch + (this.rotPitch - this.prevPitch) * 0.2F;
            this.rotYaw = this.prevYaw + (this.rotYaw - this.prevYaw) * 0.2F;
            float f2 = this.getMotionFactor();

            if (this.isInLiquid())
            {
                for (int j = 0; j < 4; ++j)
                {
                    float f3 = 0.25F;
                    this.worldObj.spawnParticle(ParticleType.WATER_BUBBLE, this.posX - this.motionX * (double)f3, this.posY - this.motionY * (double)f3, this.posZ - this.motionZ * (double)f3, this.motionX, this.motionY, this.motionZ);
                }

                f2 = 0.8F;
            }

            this.motionX += this.accelerationX;
            this.motionY += this.accelerationY;
            this.motionZ += this.accelerationZ;
            this.motionX *= (double)f2;
            this.motionY *= (double)f2;
            this.motionZ *= (double)f2;
            this.worldObj.spawnParticle(ParticleType.SMOKE_NORMAL, this.posX, this.posY + 0.5D, this.posZ, 0.0D, 0.0D, 0.0D);
            this.setPosition(this.posX, this.posY, this.posZ);
        }
        else
        {
            this.setDead();
        }
    	if(!this.worldObj.client && this.age++ >= 200)
    		this.setDead();
    }

    /**
     * Return the motion factor for this projectile. The factor is multiplied by the original motion.
     */
    protected float getMotionFactor()
    {
        return 0.95F;
    }

    /**
     * Called when this EntityFireball hits a block or entity.
     */
    protected abstract void onImpact(HitPosition movingObject);

    /**
     * (abstract) Protected helper method to write subclass entity data to NBT.
     */
    public void writeEntityToNBT(NBTTagCompound tagCompound)
    {
        tagCompound.setShort("xTile", (short)this.xTile);
        tagCompound.setShort("yTile", (short)this.yTile);
        tagCompound.setShort("zTile", (short)this.zTile);
        String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(this.inTile);
        tagCompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString());
        tagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0));
        tagCompound.setTag("direction", this.newDoubleNBTList(this.motionX, this.motionY, this.motionZ));
        tagCompound.setInteger("Age", this.age);
    }

    /**
     * (abstract) Protected helper method to read subclass entity data from NBT.
     */
    public void readEntityFromNBT(NBTTagCompound tagCompund)
    {
        this.xTile = tagCompund.getShort("xTile");
        this.yTile = tagCompund.getShort("yTile");
        this.zTile = tagCompund.getShort("zTile");

        if (tagCompund.hasKey("inTile", 8))
        {
            this.inTile = BlockRegistry.getByIdFallback(tagCompund.getString("inTile"));
        }
        else
        {
            this.inTile = BlockRegistry.getBlockById(tagCompund.getByte("inTile") & 255);
        }

        this.inGround = tagCompund.getByte("inGround") == 1;

        if (tagCompund.hasKey("direction", 9))
        {
            NBTTagList nbttaglist = tagCompund.getTagList("direction", 6);
            this.motionX = nbttaglist.getDoubleAt(0);
            this.motionY = nbttaglist.getDoubleAt(1);
            this.motionZ = nbttaglist.getDoubleAt(2);
        }
        else
        {
            this.setDead();
        }
        this.age = tagCompund.getInteger("Age");
    }

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

    public float getCollisionBorderSize()
    {
        return 1.0F;
    }

    /**
     * Called when the entity is attacked.
     */
    public boolean attackEntityFrom(DamageSource source, int amount)
    {
//        if (this.isEntityInvulnerable(source))
//        {
//            return false;
//        }
//        else
//        {
        this.setBeenAttacked();

        if (source.getEntity() != null)
        {
            Vec3 vec3 = source.getEntity().getLookVec();

            if (vec3 != null)
            {
                this.motionX = vec3.xCoord;
                this.motionY = vec3.yCoord;
                this.motionZ = vec3.zCoord;
                this.accelerationX = this.motionX * 0.1D;
                this.accelerationY = this.motionY * 0.1D;
                this.accelerationZ = this.motionZ * 0.1D;
            }

            if (source.getEntity() instanceof EntityLiving)
            {
                this.shootingEntity = (EntityLiving)source.getEntity();
            }

            return true;
        }
        else
        {
            return false;
        }
//        }
    }

    /**
     * Gets how bright this entity is.
     */
    public float getBrightness(float partialTicks)
    {
        return 1.0F;
    }

    public int getBrightnessForRender(float partialTicks)
    {
        return 15728880;
    }
    
    public int getTrackingRange() {
    	return 64;
    }
    
    public int getUpdateFrequency() {
    	return 1; // 10
    }
    
    public boolean isSendingVeloUpdates() {
    	return false;
    }
	
//	public int getPacketData() {
//		return this.shootingEntity != null ? this.shootingEntity.getId() : 0;
//	}
	
//	public boolean hasSpawnVelocity() {
//		return false;
//	}
    
    public EntityType getType() {
    	return EntityType.PROJECTILE;
    }
}
