-- Generates a heartbeat connection for every audio visual / tween in the given schema file

function SchemaProcessor:Process(isSeeking)
	print("Processing")

	local success, err = pcall(function()
		self.schema:Run()
		if not isSeeking then
			self.schema:cacheInitialTweenProperties()
		end

		self.schema:resetTweenObjects()
		self.schema.OrderedConfigs = self.schema:orderConfigs()

		self.connection = self.RunService.Heartbeat:Connect(function()
			for _, data in pairs(self.schema.OrderedConfigs) do
				local config = data.config
				local startTime = data.startTime

				if self.timePosition.Value >= startTime and config.Processed[startTime] == false then
					config.Processed[startTime] = true
					coroutine.wrap(function()
						config:Process(self, startTime)
					end)()
				end
			end
		end)

		self.Maid:add(self.connection)
		self.Maid:add(self.schema.Maid, "clean")
	end)

	if not success then
		warn("Run errored for your scene!")
		warn(err)
	end
	return success, err
end

function SchemaProcessor:EndScene()
	print("End of scene. Running OnEndScene for Schema")
	local success, err = pcall(function()
		self.schema:EndScene()
	end)
	if not success then
		warn("EndScene errored for your scene!")
		warn(err)
	end
	return success, err
end

function SchemaProcessor.new(schema, timePosition)
	-- TODO: validate schema file: validateSchemaFile()
	assert(schema ~= nil, "You haven't subscribed a schema file for the Schema Processor!")
	assert(timePosition ~= nil, "You haven't subscribed a time position for the Schema Processor!")

	local self = {
		Maid = Maid.new(),
		schema = schema,
		timePosition = timePosition,
		processingPool = {},
	}

	setmetatable(self, SchemaProcessor)

	self.Maid:add(self.schema.Maid, "clean")

	return self
end

function SchemaProcessor:SetPaused(isPaused)
	self.isPaused = isPaused
end

function SchemaProcessor:CleanUp()
	self.Maid:clean()
end

return SchemaProcessor
