local upvec = {x = 0, y = 1, z = 0}
local function can_see(posa, posb)
	posa = vector.add(posa, upvec)
	posb = vector.add(posb, upvec)
	
	return minetest.line_of_sight(posa, posb)
end

-- Attack the player
function defense_mob_api.library.hunt(self)
	local target = self.target
	
	
	if not target.ref
	then
		return
	end
	if target.distance <= self.attack_range
	then
		self:try_attack(target.ref)
	end
	
	if target.distance > self.attack_range or
		target.distance < self.attack_range / 2 - 1
	then
		local pos = self.object:get_pos()	
		
		local los = can_see(pos, target.pos)
		if los
		then
			self.following_stage = 0
		end
		local smart_dest = nil
		if not los and self.swarm
		then
			--TODO: swarm pathfinding
			--look in swarm for next member that sees target and follow
			--if unsuccessful, look in swarm for next following member and follow
			--if unsuccessful, look in swarm for next member that sees someone following
			local nearest_with_los
			local nearest_stage = math.huge
			local nearest_pos
			self.swarm:alert(pos, 100, function(entity, distance)
					if entity.following_stage <= nearest_stage
					then
						local epos = entity.object:get_pos()
						if can_see(pos, epos)
						then
							nearest_with_los = entity
							nearest_stage = entity.following_stage
							nearest_pos = epos
						end
					end
				end)
			if nearest_pos
			then
				self.smart_dest = nearest_pos
				self.following_stage = nearest_stage + 1
			end
		end
		if not smart_dest and not los and self.smart_path
		then --Do pathfinding
			smart_dest = defense_mob_api.pathfinder:get_waypoint(self.name, pos.x, pos.y, pos.z)
		end

		if smart_dest
		then
			self.destination = smart_dest
		else
			local r = math.max(0, self.attack_range - 2)
			local dir = vector.aim(target.pos, pos)
			self.destination = vector.add(target.pos, vector.multiply(dir, r))
		end
	end
end
