require('pathfinding/grid');
require('pathfinding/math');

PolyGrid	=	class.new(Grid);

function PolyGrid:constructor(polygons, actorSize)--nodes)
	self.polygons	=	polygons or {};
	--self.nodes		=	nodes or {};

	-- Generate nodes out of polygons
	self.nodes		=	{};
	for i,v in pairs(self.polygons) do
		--local offsetPoly = v:offset(actorSize);

		-- Usually should be 1, but complex polygons might split a solution into parts
		local solutions = clipper.offset(v.vertices, actorSize, 'miter');

		for s,solution in pairs(solutions) do
			for j,k in pairs(solution) do
				table.insert(self.nodes, Node(k.x, k.y));
			end
		end
	end

	for i,v in pairs(self.nodes) do
		printf("(%0.3f, %0.3f),", v.x, v.y);
	end
	print();

	-- Check visibility between all nodes; add connections between visible nodes
	for i,v in pairs(self.nodes) do
		for j,k in pairs(self.nodes) do
			if( v ~= k ) then -- We don't want to try connecting to ourselves
				local vis = self:checkVisibility(v,k);
				if( vis ) then
					-- Add a connection both ways
					v:addConnection(k);
					k:addConnection(v);
					printf("Nodes (%0.3f, %0.3f) and (%0.3f, %0.3f) have visibility\n", v.x, v.y, k.x, k.y);
				end
			end
		end
	end
end


-- Check if there's visibility between two nodes, returns boolean
function PolyGrid:checkVisibility(node1, node2)
	-- Iterate over every segment in all polygons, check for line collisions
	for i,polygon in pairs(self.polygons) do
		for j,vertex in pairs(polygon:getVertices()) do
			local v1 = polygon:getVertex(j);
			local v2 = polygon:getVertex(polygon:nextIndex(j));

			local intersection = lineIntersection(node1, node2, v1, v2, true);
			if( intersection ~= nil ) then
				return false;
			end
		end
	end

	return true;
end

function PolyGrid:addPolygon(poly)
	table.insert(self.polygons, poly);
end