package common.ai;

import common.entity.npc.EntityNPC;
import common.entity.projectile.EntityBox;
import common.entity.types.EntityLiving;
import common.util.BlockPos;

public class AIFlyingBoxAttack extends EntityAIBase
{
    private EntityNPC entity;
    private int delay;
    private int charge;

    public AIFlyingBoxAttack(EntityNPC entity)
    {
        this.entity = entity;
//        this.setMutexBits(3);
    }

    public boolean shouldExecute()
    {
        EntityLiving tgt = this.entity.getAttackTarget();
        return tgt != null && tgt.isEntityAlive();
    }

    public void startExecuting()
    {
        this.delay = 0;
        this.charge = 0;
    }

    public void updateTask()
    {
    	if (this.delay <= 0)
        {
            this.delay = this.entity.getRNG().excl(10, 20);
            
            int k3 = this.charge;
            ++this.charge;
            
            if (k3 > 15)
            {
                float f = 10.0F;
                float f1 = 5.0F;
                double d0 = this.entity.getRNG().drange(this.entity.posX - (double)f, this.entity.posX + (double)f);
                double d1 = this.entity.getRNG().drange(this.entity.posY - (double)f1, this.entity.posY + (double)f1);
                double d2 = this.entity.getRNG().drange(this.entity.posZ - (double)f, this.entity.posZ + (double)f);
                this.launchBoxToCoords(d0, d1, d2, true);
                this.charge = 0;
            }

            EntityLiving entity = this.entity.getAttackTarget();

            if (entity != null && entity.isEntityAlive() && this.entity.getDistanceSqToEntity(entity) <= 900.0D && this.entity.canEntityBeSeen(entity))
            {
                this.launchBoxToEntity(entity);
                this.delay = this.entity.getRNG().excl(5, 10);
                this.charge = 0;
                this.entity.getLookHelper().setLookPositionWithEntity(entity, 30.0F, 30.0F);
            }
        }
    	else {
    		--this.delay;
    	}

        super.updateTask();
    }

    private void launchBoxToEntity(EntityLiving p_82216_2_)
    {
        this.launchBoxToCoords(p_82216_2_.posX, p_82216_2_.posY + (double)p_82216_2_.getEyeHeight() * 0.5D, p_82216_2_.posZ, 
        		this.entity.getRNG().chance(100));
    }
    
    private void launchBoxToCoords(double x, double y, double z, boolean invulnerable)
    {
    	this.entity.swingItem();
        this.entity.worldObj.playAuxSFX(1014, new BlockPos(this.entity), 0);
        double d0 = this.entity.posX;
        double d1 = this.entity.posY + this.entity.height + 0.8;
        double d2 = this.entity.posZ;
        double d3 = x - d0;
        double d4 = y - d1;
        double d5 = z - d2;
        EntityBox skull = new EntityBox(this.entity.worldObj, this.entity, d3, d4, d5, invulnerable);
        skull.posY = d1;
        skull.posX = d0;
        skull.posZ = d2;
        this.entity.worldObj.spawnEntityInWorld(skull);
    }
}