-- Gives the player an upgrade for completing a lap

function WaypointController:ProvideLapReward()
	AddUpgradeEvent:FireServer(self.player)
end

function WaypointController:ProvideCheckpointReward()
	TouchCheckpointEvent:FireServer(self.player)
end

function WaypointController:UpdateWaypoint()
	self.waypointPath:Destroy()
	self.WaypointPathReached:Disconnect()
	self.NodeReached:Disconnect()
	self.FinishedMoving:Disconnect()
	
	if self.currentWaypointIndex == #waypoints then
		-- Player is at the last waypoint
		self.currentWaypointIndex = 1
		self.currentWaypoint = waypoints[self.currentWaypointIndex]
		self:ProvideCheckpointReward()
	else
		if self.currentWaypointIndex == 1 then			
			-- Cheer
			local animateScript = character:WaitForChild("Animate")
			local animation = animateScript:WaitForChild("cheer"):GetChildren()[1]
			if animation then
				local track = humanoid:LoadAnimation(animation)
				track.Priority = Enum.AnimationPriority.Action
				track:Play()
			end
		else
			-- Player has more waypoints left
			self:ProvideCheckpointReward()
		end
		
		self.currentWaypointIndex = self.currentWaypointIndex + 1
		self.currentWaypoint= waypoints[self.currentWaypointIndex]
	end
	
	self.waypointPath = WaypointPath.new(self.player, self.humanoidRoot.Position,
		self.currentWaypoint.Position)
	self.WaypointPathReached = self.waypointPath.WaypointReached:Connect(
		function()
			self:UpdateWaypoint()
		end)
	self.NodeReached = self.waypointPath.NodeReached:Connect(
		function()
			self._CooldownFinishedEvent:Fire()
		end)
	self.FinishedMoving = self.waypointPath.FinishedMoving:Connect(
		function()
			self:StopTracking()
		end)
	
	self.waypointPath:MoveTo()
end


return WaypointController
