-------------------------------------------------------------------------------
-- Core:


local MAX_PATHS = 10

local pathfindingService = game:GetService("PathfindingService")


local function SimplifyPointsStraight(points)
	local simplified = {}
	local i = 1
	while (i < #points) do
		local pt = points[i]
		table.insert(simplified, pt)
		if (i < #points) then
			local ptNext = points[i + 1]
			local dx, dy, dz = (ptNext.x - pt.x), (ptNext.y - pt.y), (ptNext.z - pt.z)
			for j = i+1, #points do
				i = j
				local ptLast = points[i - 1]
				local pt2 = points[i]
				local dx2, dy2, dz2 = (pt2.x - ptLast.x), (pt2.y - ptLast.y), (pt2.z - ptLast.z)
				if (dx ~= dx2 or dy ~= dy2 or dz ~= dz2) then
					i = (i - 1)
					break
				end
			end
		end
	end
	table.insert(simplified, points[#points])
	return simplified
end


local function SimplifyPointsDiagonal(points)
	local simplified = {}
	local i = 3
	while (i < #points) do
		local p1 = points[i - 2]
		local p2 = points[i - 1]
		local p3 = points[i]
		local a = (p1 - p2).magnitude
		local b = (p2 - p3).magnitude
		local c = (p1 - p3).magnitude
		table.insert(simplified, p1)
		if (a == b) then
			i = (i + 2)
		else
			i = (i + 1)
		end
	end
	table.insert(simplified, points[#points])
	return simplified
end


function CreatePathObject(paths, points, finalStatus)
	local path = {}
	local api = {}
	api.Status = finalStatus
	function api:GetPointCoordinates()
		return points
	end
	function api:CheckOcclusionAsync(start)
		local n = 0
		local startIndex = 1
		for i,p in pairs(paths) do
			local numPoints = #p:GetPointCoordinates()
			n = (n + numPoints)
			if (n >= start) then
				startIndex = i + 1
				local test = p:CheckOcclusionAsync(n - numPoints + start)
				if (test ~= -1) then
					return (n - numPoints + test)
				end
				break
			end
		end
		for i = startIndex, #paths do
			local p = paths[i]
			local numPoints = #p:GetPointCoordinates()
			n = (n + numPoints)
			if (numPoints > 0) then
				local test = p:CheckOcclusionAsync(1)
				if (test ~= -1) then
					return (n - numPoints + test)
				end
			end
		end
		return -1
	end
	return setmetatable(path, {
		__metatable = true;
		__index = api;
		__newindex = function()
			error("Cannot edit Path")
		end;
	})
end

