package me.otisdiver.otisprojectile.targeting;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;

import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.projectiles.ProjectileSource;

import me.otisdiver.otisprojectile.OtisProjectile;
import me.otisdiver.otisprojectile.Utils;

public class EnderPearlTargeter extends Targeter {

    // Target we're trying to get to.
    private Entity target;

    public EnderPearlTargeter(OtisProjectile main, Projectile projectile) {
        super(main, projectile);
    }

    @Override
    public void updateTarget() {
        if (isProjectileGone()) {
            cancelTargetingTask();
            return;
        }
        
        if (target == null) return;
        projectile.setVelocity(target.getLocation().toVector());
    }

    @Override
    public boolean beginTargeting() {
        // Find the Player that shot the ender pearl. Fails if a player didn't shoot it.
        ProjectileSource ps = projectile.getShooter();
        if (!(ps instanceof Player)) return false;
        Player player = (Player) ps;
        
        // Find the nearest living entity to the block where the player is looking
        // TODO: better solution via NMS
        Block targetBlock = player.getTargetBlock((Set<Material>) null, 64);
        ArrayList<Entity> entities = new ArrayList<Entity>(Arrays.asList(targetBlock.getChunk().getEntities()));
        target = Utils.getNearestEntityInList(targetBlock.getLocation(), entities);
        
        // Start targeting, report success of this task.
        return super.beginTargeting();
    }

}

@@ -115,13 +115,68 @@
 til.
-Set;%0A
+Iterator;%0Aimport java.util.Set;%0A%0Aimport org.bukkit.Location;
 %0Aimp
@@ -910,16 +910,55 @@
         
+%0A        Location projectileLocation = 
 projecti
@@ -964,53 +964,284 @@
 ile.
-setVelocity(target.getLocation().toVector());
+getLocation();%0A        Location targetLocation = target.getLocation();%0A        %0A        if (Utils.calculateDistance(projectileLocation, targetLocation) %3E 4) %7B%0A            projectile.setVelocity(Utils.getLocationsVectorDifference(projectileLocation, targetLocation));%0A        %7D
 %0A   
@@ -1863,109 +1863,417 @@
     
-target = Utils.getNearestEntityInList(targetBlock.getLocation(), entities);%0A        %0A        // Start
+/// Exclude the player%0A        Iterator%3CEntity%3E it = entities.iterator();%0A        while (it.hasNext()) %7B%0A            Entity e = it.next();%0A            if (player.equals(e)) it.remove();%0A        %7D%0A        target = Utils.getNearestEntityInList(targetBlock.getLocation(), entities);%0A        %0A        // Make the player follow the pearl.%0A        projectile.setPassenger(player);%0A        %0A        // Start (actual)
  tar

Improve ender pearl targeting (incomplete)