package hmggirlfront.entity.mob;

import java.util.List;

import gvclib.entity.EntityB_Bullet;
import gvclib.entity.living.AI_Damage;
import gvclib.entity.living.AI_EntityWeapon;
import gvclib.entity.living.AI_EntityWeapon_new;
import gvclib.entity.living.EntityGVCLivingBase;
import gvclib.event.GVCSoundEvent;
import gvclib.network.GVCLClientMessageKeyPressed;
import gvclib.network.GVCLPacketHandler;
import gvclib.world.GVCExplosionBase;
import hmggirlfront.GFSoundEvent;
import hmggirlfront.mod_GirlFront;
import hmggirlfront.entity.mob.ai.IBCAI_EntityMoveS;
import hmggirlfront.event.level.WorldDifficultyLevel_new;
import hmggirlfront.network.GFClientMessageKeyPressed;
import hmggirlfront.network.GFPacketHandler;
import hmggirlfront.world.WorldDifficultyLevel;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.MoverType;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIFleeSun;
import net.minecraft.entity.ai.EntityAIRestrictSun;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.ai.RandomPositionGenerator;
import net.minecraft.entity.monster.IMob;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.SoundEvents;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.BossInfo;
import net.minecraft.world.BossInfoServer;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class EntityIBCBoss08 extends EntityIBCBase implements IIBCBoss{

	private final BossInfoServer bossInfo =
			(BossInfoServer)(new BossInfoServer(this.getDisplayName(), BossInfo.Color.PURPLE, BossInfo.Overlay.PROGRESS)).setDarkenSky(true);
	
	public EntityIBCBoss08(World worldIn) {
		super(worldIn);
		this.setSize(1F, 2.5F);
		this.boss = true;
		aitypemax = 60;
		aitypemax2 = 60;
		aitypemaxset2 = 2;
		this.experienceValue = 300;
		
		aitype_auto = false;
		aitype2_auto = false;
	}

	protected void initEntityAI() {
		this.tasks.addTask(1, new EntityAISwimming(this));
		this.tasks.addTask(2, new EntityAIRestrictSun(this));
		this.tasks.addTask(3, new EntityAIFleeSun(this, 1.0D));
	}

	protected void applyEntityAttributes() {
		super.applyEntityAttributes();
		this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(1000D);
		this.getEntityAttribute(SharedMonsterAttributes.KNOCKBACK_RESISTANCE).setBaseValue(20D);
	}

	protected void setEquipmentBasedOnDifficulty(DifficultyInstance difficulty) {
		super.setEquipmentBasedOnDifficulty(difficulty);
		
	}
	
	public SoundEvent  DamegeSound = SoundEvents.BLOCK_ANVIL_LAND;
	public boolean attackEntityFrom(DamageSource source, float par2)
    {
    	Entity entity;
    	entity = source.getImmediateSource();
    	Entity entity2 = source.getTrueSource();
    	
		if(entity != null && entity2 != null){
			if(entity2 instanceof IMob){
	    		return false;
	        }else
	        {
				par2 = par2 * AI_Damage.newAntiBullet(this, entity, par2, 0.25F, 1.0F, 1.0F, 1.0F);
				if(par2 <= 0.0) {
					this.playSound(DamegeSound, 1F, 1F);
				}
				boolean fla = false;
				if(par2 <= 2.0) {
					fla = true;
				}
				if(entity instanceof EntityB_Bullet)
				{
					EntityB_Bullet bullet = (EntityB_Bullet) entity;
					if(bullet.bulletDameID == 1 || bullet.bulletDameID == 3) {
					}else {
						fla = true;
					}
		        }
				if(fla){
					anti_bullet_tate = 5;
		        	if(FMLCommonHandler.instance().getMinecraftServerInstance() != null) {
		    			for (EntityPlayerMP player : FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().getPlayers())
		                {
		    				GFPacketHandler.INSTANCE2.sendTo(new GFClientMessageKeyPressed(600,  this.getEntityId(), anti_bullet_tate), player);
		                }
		    		}
				}
				return super.attackEntityFrom(source, par2);
			}
		}else{
			return super.attackEntityFrom(source, par2);
		}
    }
	
	protected void dropEquipment(boolean wasRecentlyHit, int lootingModifier)
	{
    }
	
    
	public void onUpdate()
    {
        super.onUpdate();
        if (!this.world.isRemote && this.world.getDifficulty() == EnumDifficulty.PEACEFUL && this.getcanDespawn() == 0)
        {
            this.setDead();
        }
    }
    
	protected void onDeathUpdate() {
		//super.onDeathUpdate();
		++deathTime;
		if(!this.world.isRemote && this.deathTime == 1) {
			GVCExplosionBase.ExplosionKai(this, this, this.posX + 0, this.posY + 0, this.posZ + 0, 2, false,  false);
		}
		if(this.deathTime == 200) {
			//WorldDifficultyLevel.setLevel(mod_GirlFront.INSTANCE, this.world, 6, this, "hmggirlfront.cor.level6.name");
			WorldDifficultyLevel_new.setLevel(mod_GirlFront.INSTANCE, this.world, 8, "hmggirlfront.cor.level11.name");
		}
		if(!this.world.isRemote && this.deathTime == 200) {
			GVCExplosionBase.ExplosionKai(this, this, this.posX + 0, this.posY + 0, this.posZ + 0, 2, false,  false);
			this.BossDrop();
			this.setDead();
		}
	}
	
	public void getbeacon() {
    	int i = 64;
    	if(this.cooltime6 > 100 && this.getMoveT() == 1) {
    		double x = Math.abs(this.posX - this.getMoveX());
    		double y = Math.abs(this.posY - this.getMoveY());
    		double z = Math.abs(this.posZ - this.getMoveZ());
    		if(x > 50 && z > 50) {
    			this.setPositionAndUpdate(this.getMoveX(), this.getMoveY(), this.getMoveZ());
    		}
    		if(y > 30) {
    			this.setPositionAndUpdate(this.getMoveX(), this.getMoveY(), this.getMoveZ());
    		}
    		if(this.targetentity == null) {
    			//this.setPositionAndUpdate(this.getMoveX(), this.getMoveY(), this.getMoveZ());
    		}
    		
    		this.cooltime6 = 0;
    	}
    	
    }
	
	@SideOnly(Side.CLIENT)
    public int getBrightnessForRender()
    {
        return 15728880;
    }

    /**
     * Gets how bright this entity is.
     */
    public float getBrightness()
    {
        return 1.0F;
    }
	
    @Override
	public void AIType2_Change() {
		super.AIType2_Change();
		 
	}
    
    
    /**
	 * Called frequently so the entity can update its state every tick as
	 * required. For example, zombies and skeletons use this to react to
	 * sunlight and start to burn.
	 */
    int self_ex = 0;
	public void onLivingUpdate() {
		super.onLivingUpdate();
		this.biped = true;
		this.reload_time1 = 60;
		this.magazine = 32;
		if(this.getRemain_L() <= 0){
			++reload1;
			if(reload1 == reload_time1 - 10){
				this.playSound(GVCSoundEvent.reload_mag, 1.0F, 1.0F);
			}
			if(reload1 >= reload_time1){
				this.setRemain_L(this.magazine);
				reload1 = 0;
			}
		}
		
		float sp = 0.02F;
		Vec3d looked = this.getLookVec();
		
		boolean exflag = false;
		if(this.getMoveT() == 0) {
			this.setMoveT(1);
			this.setMoveX((int)this.posX);
			this.setMoveY((int)this.posY);
			this.setMoveZ((int)this.posZ);
		}
		int max = 60;
		int range = 60;
		int attack_range = 60;
		if(this.getHealth() > 0.0F) {
			AI_EntityWeapon.getTargetEntity(this, 60, 20, 20);
	//		IBCAI_EntityMoveS.newmove(this, 0, sp, 0, 30, 60, 60);
			this.newmove(this, 1, sp, max, range, attack_range);
			this.bossInfo.setPercent(this.getHealth() / this.getMaxHealth());
	//		this.getbeacon();
	//		this.motionY *= 0.2F;
		}
		
		
//		IBCAI_EntityMoveS.newmove(this, 0, sp, 0, max, range, attack_range);
		
		this.updateArmSwingProgress();
		this.getTargetEntity_isLiving();
		
		{
			if(this.getAIType2() != 1) {
				 if(!this.world.isRemote)++aitypetime2;
			    	if(aitypetime2 >= aitypemax2){
			    		aitypetime2 = 0;
			    		int ra = this.getAIType2();
			    		if(ra < aitypemaxset2) {
			    			++ra;
			    		}else {
			    			ra = 0;
			    		}
			    		this.setAIType2(ra);
			    	}
			    	if(FMLCommonHandler.instance().getMinecraftServerInstance() != null) {
						for (EntityPlayerMP playermp : FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().getPlayers()) {
							GVCLPacketHandler.INSTANCE2.sendTo(new GVCLClientMessageKeyPressed(2012, this.getEntityId(), aitypetime2), playermp);
						}
					}
			 }
		}
	
		
		if(AI_EntityWeapon.getRange(this, 60, 20, 20) && this.discover_count > 40 - (this.world.getDifficulty().getDifficultyId() * 5)){
			if(this.getAIType2() != 1) {

				this.cooltime2 = 0;
				
				if(this.cooltime >= 30 && this.getRemain_L() > 0)
				{
	    			this.counter1 = true;
	    			this.cooltime = 0;
				}
	    		if(this.counter1 && this.gun_count1 >= 2 && this.getRemain_L() > 0){
	    			{
						String model = "hmggirlfront:textures/entity/bullet_shot.mqo";
			    		String tex = "hmggirlfront:textures/entity/bullet_shot.png";
			    		String modelf = "hmggirlfront:textures/entity/mflash_ibc.mqo";
			    		String texf = "hmggirlfront:textures/entity/mflash_ibc.png";
			    		SoundEvent sounds = GFSoundEvent.fire_ibc_rifle;
			    		if(sounds == null) {
			    			sounds = SoundEvent.REGISTRY.getObject(new ResourceLocation(mod_GirlFront.MOD_ID, "fire_ibc_rifle"));
			    		}
			        			AI_EntityWeapon_new we = new AI_EntityWeapon_new(this, this);
								we.id = 0;
								we.model = model;
								we.tex = tex;
								we.modelf = modelf;
								we.texf = texf;
								we.ftime = 0;
								we.sound = sounds;
								if(this.getRemain_L() %2 == 0) {
									we.f = -1.57F;
								}else {
									we.f = 1.57F;
								}
								we.w = 0.3F * 1.5;
								we.h = 1.5 * 1.5;
								we.z = 0.75;
								we.bx = 0.2F;
								we.by = 1.5;
								we.bz = 0.0;
								we.follow_rote = true;//向いている方向に
								we.xoffset = 0;
								we.yoffset = 0;
								we.px = this.posX;
								we.py = this.posY;
								we.pz = this.posZ;
								we.lock = looked;
								we.rote = this.rotationYawHead;
								we.maxy = 20;
								we.miny = 10;
								
								we.power = 5 + this.world.getDifficulty().getDifficultyId();
								we.damegetime = false;
								we.speed = 2F;
								we.bure = 3F;
								we.ex = 0;
								we.extrue = false;
								we.kazu = 1;
								we.gra = 0.029;
								we.maxtime = 80;
								we.dameid = 0;
								we.Attacktask(this, this, 60);
					}
					this.gun_count1 = 0;
					if(this.firetrue){
						this.setRemain_L(this.getRemain_L() - 1);
					}
					++this.countlimit1;
				}
				if(this.countlimit1 >= 4){
					this.gun_count1 = 0;
					this.counter1 = false;
					this.countlimit1 = 0;
				}
				/*if(aitypetime > 40) {
					this.aitypetime  = aitypemax;
				}***/
			}
			else if(this.getAIType2() == 1) {
			if(this.targetentity != null){
				if(this.cooltime2 == 20)
				{
					this.counter2 = true;
					this.motionY = 1.0F;//1.25
					attacked = false;
					if(this.targetentity != null) {
						pppx = this.targetentity.posX;
						pppy = this.targetentity.posY;
						pppz = this.targetentity.posZ;
					}
				}
				if(this.cooltime2 >= 22 && this.cooltime2 < 30) {
					if(this.motionY <= 0F)this.motionY = 0F;
				}
				{
					if(this.cooltime2 == 30) {
						if(this.targetentity != null) {
							mitarget(pppx, pppy, pppz);
						}
					}
					
					if(this.counter2){
						Vec3d lock = Vec3d.fromPitchYaw(this.rotationPitch, this.rotationYaw);
						float d = 3;
						List<Entity> llist = this.world.getEntitiesWithinAABBExcludingEntity(this, this
								.getEntityBoundingBox().expand(this.motionX, this.motionY, this.motionZ).grow(1D));
						if (llist != null) {
							for (int lj = 0; lj < llist.size(); lj++) {
								Entity entity1 = (Entity) llist.get(lj);
								if (entity1.canBeCollidedWith() && entity1 instanceof EntityLivingBase && entity1 != null) {
									if(entity1 != this && entity1 != this.getControllingPassenger()){
										{
											entity1.attackEntityFrom(DamageSource.causeMobDamage(this), 15);
											//this.world.spawnParticle(EnumParticleTypes.EXPLOSION_HUGE, this.posX, this.posY + 0D, this.posZ, 0.0D, 0.0D, 0.0D, 1);
											
										}
									}
								}
							}
						}
					}
					if(collidedVertically && this.counter2 && this.cooltime2 >= 31) {
						this.counter2 = false;
						GVCExplosionBase.ExplosionKai(this, this, this.posX + 0, this.posY + 0, this.posZ + 0, 3, false,  false);
					}
				}
				
				if(this.cooltime2 >= 50 && this.cooltime2 < 53){
					double speed = 1.0F;
					double mox = 0;
					double moy = 0.3F;//0.4
					double moz = 0;
					float yaw = this.rotationYaw * (2 * (float) Math.PI / 360);
					mox -= MathHelper.sin(yaw) * speed * -1;
					moz += MathHelper.cos(yaw) * speed * -1;
					{
						{
							this.motionX = mox;
							this.motionZ = moz;
							this.motionY = moy;
							this.move(MoverType.SELF, this.motionX, this.motionY, this.motionZ);
						}
					}
				}
				if(this.cooltime2 >= 60){
					attacked = false;
					this.counter2 = false;
					this.cooltime2 = 0;
					this.aitypetime2  = 0;
					this.setAIType2(2);
				}
			}
		}
		}
		
    	
	}
	
	public boolean attacked = false;
	
	private double pppx;
	private double pppy;
	private double pppz;
	
	private double targetDeltaX;
    private double targetDeltaY;
    private double targetDeltaZ;
	public void mitarget(double x1, double y1, double z1){
		double inaccuracy = 0.01D;
		double velocity = 4.0D;
		
		double x= x1 - this.prevPosX;
        double y = y1 - this.prevPosY;
        double z = z1 - this.prevPosZ;
        float var10 = MathHelper.sqrt(x * x + z * z) * 0.001F;
        y = y + (double)var10;
		 float f = MathHelper.sqrt(x * x + y * y + z * z);
	        x = x / (double)f;
	        y = y / (double)f;
	        z = z / (double)f;
	        //x = x + this.rand.nextGaussian() * 0.007499999832361937D * (double)inaccuracy;
	        //y = y + this.rand.nextGaussian() * 0.007499999832361937D * (double)inaccuracy;
	        //z = z + this.rand.nextGaussian() * 0.007499999832361937D * (double)inaccuracy;
	        x += this.rand.nextGaussian() * (double)(this.rand.nextBoolean() ? -1 : 1) * 0.01 * (double)inaccuracy;
	        y += this.rand.nextGaussian() * (double)(this.rand.nextBoolean() ? -1 : 1) * 0.01 * (double)inaccuracy;
	        z += this.rand.nextGaussian() * (double)(this.rand.nextBoolean() ? -1 : 1) * 0.01 * (double)inaccuracy;
	        x = x * (double)velocity;
	        y = y * (double)velocity;
	        z = z * (double)velocity;
	        this.motionX = x;
	        this.motionY = y;
	        this.motionZ = z;
	        float f1 = MathHelper.sqrt(x * x + z * z);
		
	}
	
	public void newmove(EntityGVCLivingBase entity, int id, float sp, float max, double range, double attack_range) {
		entity.sneak = false;
		boolean ta = false;
		
		{
			List<Entity> llist = entity.world.getEntitiesWithinAABBExcludingEntity(entity, entity
					.getEntityBoundingBox().expand(entity.motionX, entity.motionY, entity.motionZ).grow(range));
			if (llist != null) {
				for (int lj = 0; lj < llist.size(); lj++) {
					Entity entity1 = (Entity) llist.get(lj);
					if (entity1.canBeCollidedWith()) {
						boolean flag = entity.getEntitySenses().canSee(entity1);
						if (entity.CanAttack(entity1) && entity1 != null) {//target
							
							if (entity.targetentity == entity1
									&& ((EntityLivingBase) entity1).getHealth() > 0.0F) {
								double d5 = entity1.posX - entity.posX;
								double d7 = entity1.posZ - entity.posZ;
								double d6 = entity1.posY - entity.posY;
								double d1 = entity.posY - (entity1.posY);
								double d3 = (double) MathHelper.sqrt(d5 * d5 + d7 * d7);
								float f11 = (float) (-(Math.atan2(d1, d3) * 180.0D / Math.PI));
								{
									{
										entity.rotationYawHead = entity.rotation = entity.rote = entity.renderYawOffset 
												= -((float) Math.atan2(d5, d7)) * 180.0F / (float) Math.PI;
										entity.rotationp = entity.rotationPitch = -f11 + 0;
									}
									
									entity.noflag = 0;
									++entity.discover_count;
								}
								if (flag) {
									entity.targetentity = (EntityLivingBase) entity1;
								}else {
									++entity.noflag;
									entity.discover_count = 0;
									entity.setFTMode(0);
								}
								break;
							} 
						}//target
						
					}
				}
			}
		}
		if(!entity.getattacktask()){
			stay(entity, id);
		}else {
			if(this.getAIType2() != 1)MoveS(entity, sp);
		}
	}
	
	public void MoveS(EntityGVCLivingBase entity, double speed){
		if(!this.world.isRemote){// 1
//			if(!entity.world.isRemote)
			{
				double d5 = entity.getMoveX() - entity.posX;
				double d7 = entity.getMoveZ() - entity.posZ;
				
				double root = Math.sqrt(d5 * d5 + d7 * d7);
				
				float off = 0;
				float yaw2= -((float) Math.atan2(d5, d7)) * 180.0F / (float) Math.PI;
				float yaw = entity.rotationYaw * (2 * (float) Math.PI / 360);
				double mox = entity.motionX;
				double moy = entity.motionY;
				double moz = entity.motionZ;
				
				//if(entity.getHealth() > entity.getMaxHealth()/2) 
				if(this.getAIType2() != 1){
					double ddx = Math.abs(d5);
					double ddz = Math.abs(d7);
					if ((ddx > 2 || ddz > 2)) 
					{
						mox -= MathHelper.sin(yaw2) * speed * 1;
						moz += MathHelper.cos(yaw2) * speed * 1;
					}
					entity.stepHeight = entity.height * 0.8F;
					{
						{
							entity.motionX = mox;
							entity.motionZ = moz;
							entity.motionY = moy;
							entity.move(MoverType.SELF, entity.motionX, entity.motionY, entity.motionZ);
						}
					}
				}
				

			}
		} // 1
	}
	
	public static void stay(EntityGVCLivingBase entity, int id) {
		double xPosition = 0;
	    double yPosition = 0;
	    double zPosition = 0;
		if (entity.getIdleTime() >= 100)
        {
        }
        else if (entity.getRNG().nextInt(120) != 0)
        {
        }
        else
        {
            Vec3d vec3 = RandomPositionGenerator.findRandomTarget(entity, 10, 7);

            if (vec3 == null)
            {
            }
            else
            {
                xPosition = vec3.x;
                yPosition = vec3.y;
                zPosition = vec3.z;
            }
            entity.rotation = entity.rotationYawHead = entity.getRNG().nextInt(120) - 60;
        }
		if(id != 0) {
			entity.getNavigator().tryMoveToXYZ(xPosition, yPosition, zPosition, 1D);
		}
	}
	
	public void fall(float distance, float damageMultiplier)
    {
    }
	
	 /**
     * Add the given player to the list of players tracking this entity. For instance, a player may track a boss in
     * order to view its associated boss bar.
     */
    public void addTrackingPlayer(EntityPlayerMP player)
    {
        super.addTrackingPlayer(player);
        this.bossInfo.addPlayer(player);
    }

    /**
     * Removes the given player from the list of players tracking this entity. See {@link Entity#addTrackingPlayer} for
     * more information on tracking.
     */
    public void removeTrackingPlayer(EntityPlayerMP player)
    {
        super.removeTrackingPlayer(player);
        this.bossInfo.removePlayer(player);
    }
}