local sideStories = {}

local function createUnlockEntry(title, xstr, filename)
	return { Title = title, Xstr = xstr, Filename = filename }
end

local defaultUnlocks = {
  createUnlockEntry("A Revolutionary at the Crossroads", 11374, "ehin.txt")
}

function sideStories:unlock(title, xstr, filename)
	self:loadPlayerData()
	local entry = createUnlockEntry(title, xstr, filename)
	table.insert(self.unlocks, entry)
	self:saveData()
end

function sideStories:saveSeen(entry)
	local config = self:loadPlayerFile()
	
	for k, v in pairs(config) do
		if v["sideStories"] then
			for _, item in pairs(v["sideStories"]) do
				if item.Title == entry.Title then
					item.Seen = true
				end
			end
		end
	end
	
	self:savePlayerFile(config)
end

function sideStories:saveData()
	local datasaver = require("datasaver")
	datasaver:saveDataToFile("sideStories", self.unlocks, true)
end

function sideStories:loadPlayerData()
	local datasaver = require("datasaver")
	local config = datasaver:loadDataFromFile("sideStories", true)
	
	if not config then
		config = {}
	end
	
	self.unlocks = config
end

function sideStories:removeDuplicateTitles(data)
  local titlesSeen = {}
  local uniqueStories = {}
  local index = 1

  for _, story in ipairs(data) do
    if not titlesSeen[story.Title] then
      titlesSeen[story.Title] = true
      uniqueStories[index] = story
      index = index + 1
    end
  end

  -- Clear the original table
  for i = #data, 1, -1 do
    table.remove(data, i)
  end

  -- Copy back the unique stories
  for i, story in ipairs(uniqueStories) do
      data[i] = story
  end
end

-- Hack the global save file and pull all saved data from all players
function sideStories:loadGlobalData()
	local config = self:loadPlayerFile()
	
	self.unlocks = defaultUnlocks
	
	for k, v in pairs(config) do
		if v["sideStories"] then
			for _, item in pairs(v["sideStories"]) do
				table.insert(self.unlocks, item)
			end
		end
	end
	
	self:removeDuplicateTitles(self.unlocks)
end

function sideStories:loadPlayerFile()
	local json = require('dkjson')
	local datasaver = require("datasaver")
	local location = 'data/players'
	local id = datasaver:basicStringHash(ba.getModTitle())
	local filename = id .. '_save_data.cfg'
  
	local file = nil
	local config = {}
  
	if cf.fileExists(filename) then
		file = cf.openFile(filename, 'r', location)
		config = json.decode(file:read('*a'))
		file:close()
		
		if not config then
			ba.error('Please ensure that ' .. filename .. ' exists in ' .. location .. ' and is valid JSON.')
		end
	end

	return config
end

function sideStories:savePlayerFile(data)
	local json = require('dkjson')
	local datasaver = require("datasaver")
	local location = 'data/players'
	local id = datasaver:basicStringHash(ba.getModTitle())
	local filename = id .. '_save_data.cfg'
	
	local file = cf.openFile(filename, 'w', location)
	file:write(json.encode(data))
	file:close()
end


return sideStories
