scanreader_utils = {}

function scanreader_utils:showPopup()
	local subtitle = ba.XSTR("Scan Data Unlocked!!", 8931)
	mn.runSEXP("( show-subtitle-text !" .. subtitle .. "! 0 20 (true) (false) 2000 2000 400 )")
	local ScriptedAudio = require("soundhandler")
	local handle = ScriptedAudio:playSound("available.ogg", false)
end

function scanreader_utils:unlockScan(scan)
	local datasaver = require("datasaver")
	
	local campaign = ba.getCurrentPlayer():getCampaignFilename()
	
	local scans = datasaver:loadDataFromFile("scanUnlocks", true) or {}
    if not scans[campaign] then
		scans[campaign] = {}
	end
	
	for _, v in ipairs(scans[campaign]) do
		if v.name == scan.name then
			ba.print("Scan already exists, skipping!\n")
			return
		end
	end
	
	table.insert(scans[campaign], scan)
	datasaver:saveDataToFile("scanUnlocks", scans, true)
	scanreader_utils:showPopup()
end

function scanreader_utils:getScans()
	local datasaver = require("datasaver")
	
	local campaign = ba.getCurrentPlayer():getCampaignFilename()
	
	local scans = datasaver:loadDataFromFile("scanUnlocks", true) or {}
	
	if not scans[campaign] then
		scans[campaign] = {}
	end
	
	return scans[campaign]
end

function scanreader_utils:setSeen(name)
	local datasaver = require("datasaver")
	
	local campaign = ba.getCurrentPlayer():getCampaignFilename()
	
	local scans = datasaver:loadDataFromFile("scanUnlocks", true) or {}
    if not scans[campaign] then
		scans[campaign] = {}
	end
	
	for _, v in ipairs(scans[campaign]) do
		if v.name == name then
			v.seen = true
			datasaver:saveDataToFile("scanUnlocks", scans, true)
			break
		end
	end
end

function scanreader_utils:ResetData()
	local datasaver = require("datasaver")
	
	local campaign = ba.getCurrentPlayer():getCampaignFilename()
	
	local scans = datasaver:loadDataFromFile("scanUnlocks", true) or {}
	
	scans[campaign] = {}
	
	datasaver:saveDataToFile("scanUnlocks", scans, true)
end
