QuestManager = {}
QuestManager.Sources = {}
QuestManager.SourcesKeys = {}
QuestManager.SourcesCount = 0
QuestManager.Quests = {}

function QuestManager.sourceAvailable(params)

	local srcKeyString = "src_"..params.id

	-- Getter
	if type(params.value) ~= "boolean" then
		return gVarStore.getBool(srcKeyString)

	-- Setter
	else
		gVarStore.setBool(srcKeyString, params.value)
		return params.value
	end

end

function QuestManager.questCompleted(params)

	local questKeyString = "q_"..params.id.."_complete"

	-- Getter
	if type(params.value) ~= "boolean" then
		return gVarStore.getBool(questKeyString)

	-- Setter
	else
		gVarStore.setBool(questKeyString, params.value)
		return params.value
	end

end

function QuestManager.questAccepted(params)

	local questKeyString = "q_"..params.id.."_accepted"

	-- Getter
	if type(params.value) ~= "boolean" then
		return gVarStore.getBool(questKeyString)

	-- Setter
	else
		gVarStore.setBool(questKeyString, params.value)
		return params.value
	end

end

function QuestManager.objectivesCompleted (quest)

		-- If quest is completed it's safe to save the objective has been met as well
		-- Even if it isn't any more ... we don't care about it here.
		-- This is a care free area.
		-- Breathe in slowly.
		if QuestManager.questCompleted({id = quest.getId()}) == true then
			return true
		end

		for i=1,quest.getNumberOfObjectives() do
			if quest.isObjectiveCompleted(i) == false then
				return false
			end
		end
		return true
end



function QuestManager.registerSource(key, source)
	QuestManager.Sources[key] = source
	table.insert(QuestManager.SourcesKeys, key)
	QuestManager.Sources[QuestManager.SourcesCount+1] = source
	QuestManager.SourcesCount = QuestManager.SourcesCount + 1
end

function QuestManager.registerQuest(sourceKey, questKey, quest)
	local source = QuestManager.Sources[sourceKey]
	source.Quests[questKey] = quest
	QuestManager.Quests[questKey] = quest
	table.insert(source.QuestsKeys, questKey)
	source.Quests[source.QuestsCount+1] = quest
	source.QuestsCount = source.QuestsCount + 1
end

function QuestManager.checkActiveQuests ()
	for k,quest in pairs(QuestManager.Quests) do
		if QuestManager.questAccepted({id = k}) == true and QuestManager.questCompleted({id = k}) == false then
			if QuestManager.objectivesCompleted(quest) == true and quest.shouldAutoCollectRewards() == true then
				gGUI.showNotification({
					text = gUtils.translate("quest_completed_notification").." "..quest.getName(),
					sound = gSoundManager.getSound(14, SoundGroup.SFX)
				})
				QuestManager.questCompleted({id = k, value = true})
				quest.onComplete()
			end
		end
	end
end

gQuestsManager.loadSources({
	"general",
	"merchant"
})

gQuestsManager.loadQuests({
	"gettingstarted",
	"returnsafely",
	"spicerun"
})
