local BtA = {}

-- BtA specific. Takes a mission filename and returns a numeric value that represents
-- the mission's place in the entire game as a whole. Returns a negative value if there
-- is an unexpected parsing issue with the mission filename.
function BtA:getGameProgress(mission)

	--Got nil for the filename, so grab the previous mission.
	if mission == nil then
		mission = ca.getPrevMissionFilename()
	end
  
	--It's still nil, so grab the campaign file.
	if mission == nil then
		mission = ba.getCurrentPlayer():getCampaignFilename()
	end
  
	--If it's still nil then we have a problem!
	if mission == nil then
		ba.warning("Utility 'getGameProgression' was not able to evaluate a nil filename!")
		return -1
	end
  
	--Trim the extension
	mission = string.gsub(mission, "%..+$", "")

	--Not a BtA mission or name is too short!
	if string.lower(string.sub(mission, 1, 3)) ~= "bta" then
		return -1
	end
  
	local rem = string.sub(mission, 4)
  
	--Initialize values
	local a = 0
	local b = 0
	local c = 0
	local d = 0
	local e = 0
  
	--We're in an Anthology Campaign!
	if string.sub(rem, 1, 1) == "-" then
		rem = rem:sub(2)
    
		local designation = ""
    
		for i = 1, #rem do
			local char = string.sub(rem, i, i)
			if char == "_" then
				-- Stop when an underscore is encountered
				rem = string.sub(rem, i + 1)
				break
			else
				-- Append the character to the result string
				designation = designation .. char
			end
		end
		
		-- Haha, just kidding! It's the tutorial.
		if designation == "tut" then
			return 0
		end
    
		if designation == "af" then
			a = 1500
		elseif designation == "lna" then
			a = 1700
		elseif designation == "ac" then
			a = 3500
		elseif designation == "rs" then
			a = 0
		elseif designation == "gtva" then
			a = 4000
		elseif designation == "tem" then
			a = 4500
		else
			--not a valid BtA Anthology Campaign mission!
			return -2
		end
  
	--Main or Demo campaign!
	else
		--Get the campaign numerical designation
		a = tonumber(string.sub(rem, 1, 1))
		if a ~= nil and a > 0 then
			a = a * 1000 --Make it the thousands place
			rem = string.sub(rem, 3)
		else
			--Not a campaign designation? Error!
			return -3
		end
	end
      
	--Main or Demo campaign designation?
	if string.lower(string.sub(rem, 1, 1)) == "m" then
		b = 100 --Hundreds place
	end
      
	rem = string.sub(rem, 2)
  
	--If we stop here then it's probably a campaign file
	if #rem > 0 then
		--Get the campaign act numerical designation
		c = tonumber(string.sub(rem, 1, 1))
		if c ~= nil and c > 0 then
			c = c * 10 --Make it the tens place
			rem = string.sub(rem, 3)
		else
			--Not an act designation? Error!
			return -4
		end
      
		--Get the campaign mission numerical designation
		--Here's hoping we never have more than 9 missions in an act or this whole formula breaks!
		d = tonumber(string.sub(rem, 1, 2))
		if d ~= nil and d > 0 then
			rem = string.sub(rem, 3)
		else
			--Not a mission designation? Error!
			return -5
		end
      
		--Loop, training, or otherwise?
		if #rem > 0 then
			e = 0.5
		end
	end
  
	--Catch any unsupported issues
	if a == nil or b == nil or c == nil or d == nil or e == nil then
		return -6
	end

	return a + b + c + d + e
  
end

function BtA:GetLicensing()

	if not parse.readFileText("credits-footer.tbl", "data/tables") then
		return ""
	end
	
	local text = "<br></br><br></br>"
	
	while(not parse.optionalString("#end")) do
		local thisString = parse.getString()
		
		text = text .. thisString .. "<br></br>"
	end
	
	parse.stop()
	
	--Get just the license portion of the footer. This is kinda dumb but there's not really a better way.
	local license_text = text:gsub(".*%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-","")
	--Remove double breaks
	license_text = license_text:gsub("<br></br><br></br>", "<br></br>")
	
	return license_text
	
end

function BtA:parseLinkItem(parentTbl)
	local name = parse.getString()
			
	local links = {}
	while parse.optionalString("$Link:") do
		table.insert(links, parse.getString())
	end
	
	if #links > 0 then
		parentTbl[name] = links
	end
end

function BtA:parseLinks(data)

	if cf.fileExists('credits_links.tbl') then
	
		local tbl = {}
	
		parse.readFileText(data, "data/tables")
		
		if parse.optionalString("#General Links") then
			tbl.generalLinks = {}
			
			while parse.optionalString("$Name:") do
				self:parseLinkItem(tbl.generalLinks)
			end
		end
		
		if parse.optionalString("#Other Links") then
			tbl.otherLinks = {}
			
			while parse.optionalString("$Name:") do
				self:parseLinkItem(tbl.otherLinks)
			end
		end
		
		if parse.optionalString("#Music Links") then
			tbl.musicLinks = {}
			
			while parse.optionalString("$Name:") do
				self:parseLinkItem(tbl.musicLinks)
			end
		end

		if parse.optionalString("#Voice Actor Links") then
			tbl.voiceLinks = {}
			
			while parse.optionalString("$Name:") do
				self:parseLinkItem(tbl.voiceLinks)
			end
		end
		
		parse.requiredString("#End")

		parse.stop()
		
		return tbl
	
	else
		return {}
	end

end

function BtA:getBonusShipAmounts()
	local numSnails = 0
	local numEagles = 0
	--This is some of the hackiest shit ever, but Eternal variables are only
	--available during campaign missions in FSO. So let's get the pilot file directly
	--and just find the data we want. That's right, SCP. I'm mucking with the player
	--file directly and there's NOTHING YOU CAN DO ABOUT IT!
	local filename = ba.getCurrentPlayer():getName() .. ".json"
	local file = cf.openFile(filename, 'r', 'data/players')
	if file:isValid() then
		local config = require('dkjson').decode(file:read('*a'))
		file:close()
		if not config then
			ba.print("Error reading the player file! Bailing!\n")
			return 0, 0
		end
		
		for i, v in ipairs(config.sections.variables.variables) do
			--Battle snails
			if v.variable_name == "BattleSnailsAvail" then
				if mn.SEXPVariables["BattleSnailsAvail"].Value ~= nil then
					ba.print("Battle Snail value found! Current count is " .. v.text .. "\n")
					numSnails = v.text
				end
			end
			--Eagle 5s
			if v.variable_name == "EagleFivesAvail" then
				if mn.SEXPVariables["EagleFivesAvail"].Value ~= nil then
					ba.print("Eagle Five value found! Current count is " .. v.text .. "\n")
					numEagles = v.text
				end
			end
		end
	else
		ba.print("Error opening the player file!\n")
	end
	
	return numSnails, numEagles
end

return BtA