package hmggirlfront.entity;

import java.util.List;
import java.util.UUID;

import javax.annotation.Nullable;

import com.google.common.base.Optional;

import gvclib.entity.EntityP_Particle;
import gvclib.entity.living.EntityGVCLivingBase;
import gvclib.entity.living.ISoldier;
import hmggirlfront.mod_GirlFront;
import hmggirlfront.items.ItemDollGunBase;
import hmggirlfront.network.GFClientMessageKeyPressed;
import hmggirlfront.network.GFPacketHandler;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.IMob;
import net.minecraft.entity.passive.IAnimals;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.MobEffects;
import net.minecraft.init.SoundEvents;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.potion.PotionEffect;
import net.minecraft.server.management.PreYggdrasilConverter;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.World;

public class EntityDoll_Dummy extends EntityDollBase implements IAnimals, ISoldier {

	public EntityDoll_Dummy(World worldIn) {
		super(worldIn);
		this.setSize(0.5F, 1.8F);
		this.biped = false;
	}

	/**0 == HG:
	 * 1 == SMG:
	 * 2 == AR:
	 * 3 == RF:
	 * 4 == MG:
	 * 5 == SG:
	 * 6 == GL*/
	public int gun_class = 0;
	
	public int evasion = 0;
	public int evasion_base = 0;
	public int power = 0;
	public int power_base = 0;
	public String bullet_type_am = "";
	public float bure = 0;
	public float bure_base = 0;
	public int rpm = 0;
	public int rpm_base = 0;
	public int pellet = 1;
	public int pellet_base = 1;
	
	
	public float doll_size = 1.0F;
	
	public int doll_armor = 0;
	public int doll_armorbase = 0;
	
	/**回復速度*/
	public int doll_hp_recovery = 40;
	
	public Item bullet_type = null;
	public String bullet_type_tab = "";
	
	public int doll_heal_time = 0;
	
	public int doll_skill = 0;
	public boolean doll_skill_can = true;
	public int doll_autoskill = 0;
	
	public ItemStack mainitem = new ItemStack((Item)null);// = nullはだめっぽい
	
	protected static final DataParameter<Optional<UUID>> OWNER_UNIQUE_ID_dummy 
	= EntityDataManager.<Optional<UUID>>createKey(EntityDoll_Dummy.class, DataSerializers.OPTIONAL_UNIQUE_ID);
	
	private static final DataParameter<Integer> dummy_id = 
    		EntityDataManager.<Integer>createKey(EntityDoll_Dummy.class, DataSerializers.VARINT);
	
	 public void writeEntityToNBT(NBTTagCompound compound)
	    {
	        super.writeEntityToNBT(compound);
	        if (this.getOwnerId_dummy() == null)
	        {
	            compound.setString("OwnerUUID_dummy", "");
	        }
	        else
	        {
	            compound.setString("OwnerUUID_dummy", this.getOwnerId_dummy().toString());
	        }
	        compound.setInteger("dummy_id", getDummyID());
	    }
	
	 public void readEntityFromNBT(NBTTagCompound compound)
	    {
	        super.readEntityFromNBT(compound);
	        String s;
	        if (compound.hasKey("OwnerUUID_dummy", 8))
	        {
	            s = compound.getString("OwnerUUID_dummy");
	        }
	        else
	        {
	            String s1 = compound.getString("Owner_dummy");
	            s = PreYggdrasilConverter.convertMobOwnerIfNeeded(this.getServer(), s1);
	        }

	        if (!s.isEmpty())
	        {
	            try
	            {
	                this.setOwnerId_dummy(UUID.fromString(s));
	            }
	            catch (Throwable var4)
	            {
	            }
	        }
	        this.setDummyID(compound.getInteger("dummy_id"));
	    }
	
	 protected void entityInit()
	    {
	    	super.entityInit();
	    	this.dataManager.register(OWNER_UNIQUE_ID_dummy, Optional.absent());
	    	this.dataManager.register(dummy_id, Integer.valueOf(1));
	    }
	 
	 public int getDummyID() {
 		return ((this.dataManager.get(dummy_id)).intValue());
 	}

 public void setDummyID(int stack) {
 		this.dataManager.set(dummy_id, Integer.valueOf(stack));
 }
	 
	@Nullable
    public EntityLivingBase getOwner_dummy()
    {
        try
        {
            UUID uuid = this.getOwnerId_dummy();
            return uuid == null ? null : this.world.getPlayerEntityByUUID(uuid);
        }
        catch (IllegalArgumentException var2)
        {
            return null;
        }
    }

	
	public void setTamedBy_dummy(EntityLivingBase player)
    {
        this.setOwnerId_dummy(player.getUniqueID());
    }
	@Nullable
    public UUID getOwnerId_dummy()
    {
        return (UUID)((Optional)this.dataManager.get(OWNER_UNIQUE_ID_dummy)).orNull();
    }

    public void setOwnerId_dummy(@Nullable UUID p_184754_1_)
    {
        this.dataManager.set(OWNER_UNIQUE_ID_dummy, Optional.fromNullable(p_184754_1_));
    }
	
    public boolean isOwner_dummy(EntityLivingBase entityIn)
    {
        return entityIn == this.getOwner_dummy();
    }
    
    
    public boolean processInteract(EntityPlayer player, EnumHand hand)
    {
    	ItemStack itemstack = player.getHeldItem(hand);
        boolean flag = !itemstack.isEmpty();
        if(flag) {
        	  {
        		if(itemstack.getItem() == mod_GirlFront.idoll_doll_dismantling) {
        			if (!this.world.isRemote) {
    					this.setDead();
    				}
        		}
        		/*if(itemstack.getItem() == mod_GirlFront.idoll_doll_repair) {
        			this.deathTime = 0;
        			this.setHealth(this.getMaxHealth());
    				itemstack.shrink(1);
    				this.playSound(SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, 1.0F, 1.0F);
    			}
        		if(itemstack.getItem() == mod_GirlFront.idoll_parts) {
    				if(this.getHealth() < this.getMaxHealth()) {
    					this.setHealth(this.getHealth() + 1);
        				itemstack.shrink(1);
    				}else {
    					this.deathTime = 0;
    					itemstack.shrink(1);
    				}
    				this.playSound(SoundEvents.ITEM_SHIELD_BREAK, 1.0F, 1.0F);
    			}*/
        	}
        	
        }
    	return true;
    }
    
    public boolean CanAttack(Entity entity){
    	if(entity instanceof IMob && ((EntityLivingBase) entity).getHealth() > 0.0F){
    		return true;
    	}else
    	{
    		return false;
    	}
    }
    
    public boolean attackEntityFrom(DamageSource source, float par2)
    {
    	Entity entity;
    	entity = source.getTrueSource();
    	
		if(entity != null){
			if(entity instanceof EntityPlayer && !mod_GirlFront.cfg_friendlyfire_player_to_doll){
				GFPacketHandler.INSTANCE2.sendToAll(new GFClientMessageKeyPressed(801, this.getEntityId()));
				return false;
			}
			if(entity instanceof EntityDollBase){
				GFPacketHandler.INSTANCE2.sendToAll(new GFClientMessageKeyPressed(801, this.getEntityId()));
	    		return false;
	        }else {
				int ran = this.world.rand.nextInt(100);
				if (ran > evasion) {
					if(doll_armor > 0) {
						/*par2 = par2 * ((100 - doll_armor*2) * 0.01F);
						if(par2 <= 1) {
							par2 = 1;
						}*/
						if(par2 <= doll_armor) {
							par2 = 1;
						}else {
							par2 = par2 - doll_armor;
						}
						this.playSound(SoundEvents.ITEM_SHIELD_BLOCK, 1F, 1F);
						GFPacketHandler.INSTANCE2.sendToAll(new GFClientMessageKeyPressed(802, this.getEntityId()));
					}
					return super.attackEntityFrom(source, par2);
				} else {
					GFPacketHandler.INSTANCE2.sendToAll(new GFClientMessageKeyPressed(801, this.getEntityId()));
					return false;
				}
	        }
		}else{
			return super.attackEntityFrom(source, par2);
		}
    }
    
    
    protected void onDeathUpdate() {
		 ++this.deathTicks;
		 this.addPotionEffect(new PotionEffect(MobEffects.GLOWING, 10, 10));
		 if(this.deathTicks == 1) {
			/* List llist = this.world.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox()
		        		.expand(this.motionX, this.motionY, this.motionZ).grow(60.0D));
				if (llist != null) {
					for (int lj = 0; lj < llist.size(); lj++) {
						Entity entity1 = (Entity) llist.get(lj);
						if (entity1.canBeCollidedWith() && entity1 != null) {
							if (entity1 instanceof EntityLivingBase && entity1 instanceof EntityPlayer)
	                        {
								if (this.isOwner((EntityLivingBase) entity1)) 
								{
									EntityPlayer player = (EntityPlayer) entity1;
									if(this.world.isRemote && this.isOwner(player) &&  player == this.getOwner()) {
					    				//player.sendMessage(new TextComponentTranslation(this.getCustomNameTag() + "hmggirlfront.order.dead.name", new Object[0]));
										TextComponentTranslation aaa = new TextComponentTranslation("hmggirlfront.order.dead.name", new Object[0]);
										//player.sendMessage(new TextComponentTranslation("hmggirlfront.order.dead.name", new Object[0]));
										player.sendMessage(new TextComponentTranslation(this.getCustomNameTag() + "  is a dangerous situation!", new Object[0]));
									break;
									}
								}
	                        }
						}
					}
				}*/
		 }
		}
    
    public boolean reset = true;
    public int owner_search = 0;
    public int search_dummy =0;
    public void onLivingUpdate() {
		super.onLivingUpdate();
		
		if (this.getHealth() > 0.0F) {
			this.deathTicks = 0;
		}
		
		GFEntityID_Dummy gfid = new GFEntityID_Dummy(this);
		int id = gfid.getID();
		
		//DollAI_ItemCatch.load(this);
		DollAI_Reload.load_dummy(this);
		
		DollAI_Level.load_dummy(this);
		
		DollAI_MasterArm.load_dummy(this);
		
		
		
		/*{
			if(this.getOwner_dummy() != null && this.getOwner_dummy() instanceof EntityDoll) {
				EntityDoll owner = (EntityDoll) this.getOwner_dummy();
				this.setMoveT(owner.getMoveT());
				 if(owner.getOwner() != null)this.setTamedBy((EntityPlayer) owner.getOwner());
			}
		}*/
		if(!this.getItemStackFromSlot(EntityEquipmentSlot.MAINHAND).isEmpty() && this.getItemStackFromSlot(EntityEquipmentSlot.MAINHAND).getItem() instanceof ItemDollGunBase) {
			ItemDollGunBase gun = (ItemDollGunBase) this.getItemStackFromSlot(EntityEquipmentSlot.MAINHAND).getItem();
			{
				int kazu = 0;
				double k = this.posX;
				double l = this.posY;
				double i = this.posZ;
				int han = 20;
				EntityDoll owner = null;


				AxisAlignedBB axisalignedbb = (new AxisAlignedBB((double) (k - han), (double) (l - han),
						(double) (i - han), (double) (k + han), (double) (l + han), (double) (i + han)))
								.grow(1);
				List<Entity> llist = this.world.getEntitiesWithinAABBExcludingEntity(this, axisalignedbb);
				if (llist != null) {
					for (int lj = 0; lj < llist.size(); lj++) {
						Entity entity1 = (Entity) llist.get(lj);
						if (entity1.canBeCollidedWith()  && entity1 != null) {
							if (entity1 instanceof EntityDoll) {
								EntityDoll doll = (EntityDoll) entity1;
								if(this.getCustomNameTag().equals(doll.getCustomNameTag())) {
									owner = doll;
									break;
								}
							}
						}
					}
				}
				if(owner != null) {
					owner_search = 0;
					this.setMoveT(owner.getMoveT());
					{
						if(this.getDummyID() == 0) {
							owner.dummy0 = this;
						}else if(this.getDummyID() == 1) {
							owner.dummy1 = this;
						}else if(this.getDummyID() == 2) {
							owner.dummy2 = this;
						}
					}
					{
						this.setHealth(owner.getHealth());
					}
					 if(owner.getOwner() != null)this.setTamedBy((EntityPlayer) owner.getOwner());
				}
			
				
				
				if (llist != null) {
					boolean flagg = false;
					for (int lj = 0; lj < llist.size(); lj++) {
						Entity entity1 = (Entity) llist.get(lj);
						if (entity1.canBeCollidedWith()  && entity1 != null) {
							if (entity1 instanceof EntityDoll_Dummy) {
								EntityDoll_Dummy doll = (EntityDoll_Dummy) entity1;
								EntityDoll_Dummy dummy = (EntityDoll_Dummy) entity1;
								if(dummy.getDummyID() == this.getDummyID() && this.getCustomNameTag().equals(dummy.getCustomNameTag())) {
									flagg = true;
									break;
									
								}
							}
						}
					}
					if(flagg) {
						++search_dummy;
						if(search_dummy > 10) {
							if (!this.world.isRemote) {
		    					this.setDead();
		    				}
						}
					}else {
						search_dummy = 0;
					}
				}
				
				
				if(owner == null) {
					++owner_search;
					if(owner_search == 10){
						//entity.world.spawnParticle(EnumParticleTypes.NOTE, 
						//		entity.posX,  entity.posY + entity.height + 1, entity.posZ, 0, 0, 0);
						if(!this.world.isRemote){
							EntityP_Particle particle = new EntityP_Particle(this.world);
							particle.setLocationAndAngles(this.posX, this.posY+this.height + 1, this.posZ, this.rotationYaw, 0.0F);
							particle.setModel("hmggirlfront:textures/particle/find.mqo");
							particle.setTex("hmggirlfront:textures/particle/find.png");
							particle.startposX = this.posX;
							particle.startposY = this.posY+this.height + 1;
							particle.startposZ = this.posZ;
							particle.timemax = 20;
							this.world.spawnEntity(particle);
						}
					}
					if (!this.world.isRemote && owner_search > 20)
			        {
			            this.setDead();
			        }
				}
				
			}
		}
		
    }
    
}
