local utils = require("utils")
local tblUtil = utils.table
local dialogs = require("dialogs")
local class = require("class")
local md = require("debugFunctions")
local async_util = require("async_util")

local RequisitionsController = class()
local selectedData = nil

local visibleFactionList = {}

ScpuiSystem.modelDraw = nil

function RequisitionsController:init()

	--Requisitions Globals
	self.inputActive = false
	self.input_id = nil
	self.submittedValue = 0
	self.currentSelection = nil
	self.currentSection = nil
	self.currentFaction = nil
	self.currentKey = nil

	self.recentSection = nil
	self.recentFaction = nil
	self.recentKey = nil

	self.totalCost = nil
	
	self.first_run = false

	--Translatable strings
	self.strings = {
		Available = {"Available", -1},
		Owned = {"Owned", -1},
		Cost = {"Cost", -1},
		Selection = {"Total", -1},
		CommandPoints = {"CP", -1},
		PerItem = {"Per Item", -1},
		Remaining = {"Remaining", -1},
		FactionIntro = {"Typically flown by the", -1},
		Type = {"Ship Type", -1},
		Maneuver = {"Maneuverability Rating", -1},
		Armor = {"Armor Rating", -1},
		Manufacturer = {"Manufactured by", -1},
		Afterburn = {"Max Afterburner Fuel", -1},
		Countermeasures = {"Countermeasure Capacity", -1},
		Power = {"Power Generator Capacity", -1},
		PowerSuffix = {"mw", -1},
		CreatedByIntro = {"Designed and Manufactured by", -1},
		Seeking = {"Weapon Type", -1},
		Range = {"Range", -1},
		Speed = {"Speed", -1},
		Damage = {"Damage Yield", -1},
		DPS = {"Damage Per Second", -1},
		ArmorFactor = {"Armor Damage", -1},
		ShieldFactor = {"Shield Damage", -1},
		SubsystemFactor = {"Subsystem Damage", -1},
		CargoSize = {"Bank Capacity Used Per Unit", -1},
		SpeedSuffix = {"m/s", -1},
		DamageSuffix = {"KEb", -1},
		DPSSuffix = {"KEb/s", -1},
		RangeSuffix = {"m", -1},
		NoReqs = {"No Requisitions Available", -1},
		Okay = {"Okay", -1},
		NeededCP = {"Total cost for the requested items is", -1},
		CurrentCP = {"You only have", -1},

		FailureText = {"Not enough Command Points available!", -1},
		FailureTitle = {"REQUISITION FAILURE", -1},
		SuccessText1 = {"Sucessfully requisitioned", -1},
		SuccessText2 = {"Total cost", -1},
		SuccessText3 = {"Amount available is now reflected in Inventory", -1},
		SuccessText4 = {"Command Points remaining", -1},
		SuccessTitle = {"REQUISITION SUCCESS", -1},
		EmptyReturn = {"Please enter a non-zero number into the text box and then submit.", -1}
	}
	self.strings.OkayKeypress = string.sub(utils.xstr(self.strings.Okay), 1, 1)

end

--Load default and current backstock values if available
function RequisitionsController:LoadData()

	backstock:LoadDataQuick()
	
	self.document:GetElementById("requisitions_requiredcp").inner_rml = "<p>" .. utils.xstr(self.strings.Selection) .. ": " .. "0" .. " " .. utils.xstr(self.strings.CommandPoints) .. "</p>"
	self.document:GetElementById("requisitions_playercp").inner_rml = "<p>" .. utils.xstr(self.strings.CommandPoints) .. " " .. utils.xstr(self.strings.Remaining) .. ": " .. backstock.current.playerCP .. "</p>"

end

function RequisitionsController:initialize(document)

    self.document = document

	---Load background choice
	self.document:GetElementById("main_background"):SetClass(ScpuiSystem:getBackgroundClass(), true)
	
	--For BtA: Set the class custom. This is a thing because Journal needs to be modular to SCPUI as well as BtA.
	--So eventually this will need a separate file to add it's own hooks into ui_topics that can then be referenced.
	--But for now we just brute force it.
	self.document:GetElementById("main_background"):SetClass("inventory_bg", true)
	
	---Load the desired font size from the save file
	self.document:GetElementById("main_background"):SetClass(("p2-" .. ScpuiSystem:getFontSize()), true)
	self.document:GetElementById("requisitions_title"):SetClass(("h2-" .. ScpuiSystem:getFontSize()), true)
	self.document:GetElementById("requisitions_counts_wrapper"):SetClass(("h1-" .. ScpuiSystem:getFontSize()), true)
	self.document:GetElementById("requisitions_cost"):SetClass(("p1-" .. ScpuiSystem:getFontSize()), true)
	self.document:GetElementById("requisitions_requiredcp"):SetClass(("s1-" .. ScpuiSystem:getFontSize()), true)
	self.document:GetElementById("requisition_amount_input"):SetClass(("p1-" .. ScpuiSystem:getFontSize()), true)
	self.document:GetElementById("requisitions_playercp"):SetClass(("p1-" .. ScpuiSystem:getFontSize()), true)
	self.document:GetElementById("submit_cont"):SetClass(("p1-" .. ScpuiSystem:getFontSize()), true)
	
	--Meant to remove focus from the input box until the player clicks on it. Doesn't currently work.
	self.input_id = self.document:GetElementById("requisition_amount_input")
	self.document:Blur(self.input_id)
	
	self.input_id.max_length = 5

	--Always reload data to reflect the latest changes
	self:LoadData()

    self:registerEventHandlers()
	
	local player = ba.getCurrentPlayer()
	local campaignfilename = player:getCampaignFilename()


	self.SelectedEntry = nil
	
	self.SelectedSection = nil
	
	if ScpuiSystem.InventorySection == nil then
		ScpuiSystem.InventorySection = 1
	end
	
	self:ChangeSection(ScpuiSystem.InventorySection)
	
	self.SelectedFaction = nil
	if visibleFactionList[1] then
		self:ChangeFaction(visibleFactionList[1])
	end
	
end

function RequisitionsController:Refresh()

	local newKey = nil
	local newFaction = nil
	local newSection = self.recentSection
	
	local refreshList = backstock.current.requisitions[selectedData]
	
	--The CheckExists function only checks for val.name, but we need val.faction so let's do it manually.
	local factionExists = false
	for i, v in ipairs(refreshList) do
		if v.faction == self.recentFaction then
			factionExists = true
		end
	end
	
	--First check if the current faction still exists
	if factionExists then
		newFaction = self.recentFaction
	else
		if refreshList[1] then
			newFaction = refreshList[1].faction
		end
	end
	
	
	--The CheckExists function only checks for val.name, but we need val.id so let's do it manually.
	local keyExists = nil
	for i, v in ipairs(refreshList) do
		if refreshList[i].name == self.recentKey and refreshList[i].faction == newFaction then
			keyExists = true
		end
	end
	
	--Now check if the current item key still exists
	if keyExists then
		newKey = self.recentKey
	else
		if refreshList[1] then
			for i, v in ipairs(refreshList) do
				if refreshList[i].faction == newFaction then
					newKey = refreshList[i].name
					break
				end
			end
		end
	end
	
	md.print("REQUISITIONS is refreshing to " .. newSection .. " " .. tostring(newFaction) .. " " .. tostring(newKey))
	
	--Actually go to the refreshed selections
	self:ChangeSection(newSection)
	if newFaction then
		self:ChangeFaction(newFaction)
		if newKey then
			self:SelectEntry(newKey)
		end
	end

end

function RequisitionsController:ChangeSection(section)

	if section then--~= self.SelectedSection then
	
		local factionList = nil
		
		self.currentSection = section
	
		if section == 1 then
			factionList = backstock.current.requisitions.ships
			selectedData = "ships"
		elseif section == 2 then
			factionList = backstock.current.requisitions.primaries
			selectedData = "primaries"
		elseif section == 3 then
			factionList = backstock.current.requisitions.secondaries
			selectedData = "secondaries"
		end
		
		ScpuiSystem.InventorySection = section

		md.print("REQUISTIONS setting selected data type to " .. selectedData)

		--If we had an old section on, remove the active class
		if self.SelectedSection then
			local oldbullet = self.document:GetElementById("btn_"..self.SelectedSection)
			oldbullet:SetPseudoClass("checked", false)
		end

		self.SelectedSection = section
		self.SelectedFaction = nil
		
		--Only create factions if there are any to create
		if factionList[1] then
			self:CreateFactions(factionList)
		else
			local list_el = self.document:GetElementById("list_logos_ul")
			ScpuiSystem:ClearEntries(list_el)
			self:ClearData()
		end
		
		if visibleFactionList[1] then
			self:ChangeFaction(visibleFactionList[1])
		end
		
		local newbullet = self.document:GetElementById("btn_"..self.SelectedSection)
		newbullet:SetPseudoClass("checked", true)


	end
	
end

function RequisitionsController:ChangeFaction(faction)

	if faction ~= self.SelectedFaction then
	
		local itemList = nil
		
		self.currentFaction = faction
	
		if selectedData == "ships" then
			itemList = backstock.current.requisitions.ships
		elseif selectedData == "primaries" then
			itemList = backstock.current.requisitions.primaries
		elseif selectedData == "secondaries" then
			itemList = backstock.current.requisitions.secondaries
		end


		if self.SelectedEntry then
			self:ClearEntry()
		end

		--If we had an old faction on, remove the active class
		if self.SelectedFaction then
			local oldlogo = self.document:GetElementById(self.SelectedFaction)
			oldlogo:SetPseudoClass("checked", false)
		end

		self.SelectedFaction = faction
		
		--Only create entries if there are any to create
		if itemList[1] then
			self:CreateEntries(itemList)
			--It's possible for the top entry in the index to be for a different faction. In that case, auto select the next one instead.
			for i, v in ipairs(itemList) do
				if itemList[i].faction == self.SelectedFaction then
					self:SelectEntry(itemList[i].name, i)
					break
				end
			end
		else
			local list_el = self.document:GetElementById("list_items_ul")
			ScpuiSystem:ClearEntries(list_el)
			self:ClearData()
		end
		
		-- check for a valid value since some sections can be empty
		if itemList[1] then
			md.print("REQUISITIONS showing list from " .. self.SelectedFaction)
			local newlogo = self.document:GetElementById(self.SelectedFaction)
			newlogo:SetPseudoClass("checked", true)
		end


	end
	
end

function RequisitionsController:CreateFactionItem(entry, index)

	local li_el = self.document:CreateElement("li")
	
	local faction = Factions:getFactionByAcronym(entry)


	li_el.inner_rml = "<img src=\"" .. faction.Logo .. " class=\"psuedo_img\"></img>" .. faction.DisplayName .. ""
	li_el.id = entry

	li_el:SetClass("requisitionslogo_element", true)
	li_el:SetClass("button_1", true)
	li_el:SetClass("req_logo", true)
	li_el:SetClass("req_logo", true)
	li_el:AddEventListener("click", function(_, _, _)
		self:ChangeFaction(entry)
	end)

	return li_el
end

function RequisitionsController:CreateFactions(factions)

	local list_el = self.document:GetElementById("list_logos_ul")

	ScpuiSystem:ClearEntries(list_el)
	
	visibleFactionList = {}
	local factionCount = 0
	
	--List which factions to create
	for i, v in ipairs(factions) do
		if not self:CheckForFaction(visibleFactionList, v.faction) then 
			visibleFactionList[factionCount + 1] = v.faction
			md.print("REQUISITIONS Found faction " .. i .. ": " .. v.faction)
			factionCount = factionCount + 1
		end
	end

	for i, v in ipairs(visibleFactionList) do
		md.print("REQUISITIONS Adding faction " .. i .. ": " .. v)
		list_el:AppendChild(self:CreateFactionItem(v, i))
	end
end

function RequisitionsController:CheckForFaction(tab, val)

	for i, v in ipairs(tab) do
		if v == val then
			return true
		end
	end
	
	return false

end

function RequisitionsController:CreateEntryItem(entry, index)

	local li_el = self.document:CreateElement("li")
	
	local displayName = entry.name

	--For weapons let's use the tech title for the list instead
	if selectedData ~= "ships" then
		displayName = tb.WeaponClasses[entry.name].Title
	end
	
	local amountRemaining = entry.amount

	li_el.inner_rml = "<span class=\"requisitionslist_left\">" .. displayName .. "</span><span class=\"requisitionslist_right\">" .. amountRemaining .. "</span>"
	li_el.id = entry.name

	li_el:SetClass("requisitionslist_element", true)
	li_el:SetClass("button_1", true)
	li_el:AddEventListener("click", function(_, _, _)
		self:SelectEntry(backstock.current.requisitions[selectedData][index].key)
	end)
	
	backstock.current.requisitions[selectedData][index].key = li_el.id

	return li_el
end

function RequisitionsController:CreateEntries(localList)

	local list_el = self.document:GetElementById("list_items_ul")

	ScpuiSystem:ClearEntries(list_el)
	self.document:GetElementById("requisition_amount_input"):SetClass("hidden", false)
	self.document:GetElementById("submit_cont"):SetClass("hidden", false)
	

	for i, v in ipairs(localList) do
		if v.faction == self.SelectedFaction then
			md.print("INVENTORY Adding item " .. i .. ": " .. v.name .. " for faction " .. v.faction)
			list_el:AppendChild(self:CreateEntryItem(v, i))
		end
	end
end

function RequisitionsController:ClearEntry()

	self.document:GetElementById(self.SelectedEntry):SetPseudoClass("checked", false)
	self.SelectedEntry = nil

end

function RequisitionsController:ClearData()

	ScpuiSystem.modelDraw = nil
	local aniWrapper = self.document:GetElementById("requisitions_view")
	aniWrapper:RemoveChild(aniWrapper.first_child)
	self.document:GetElementById("requisitions_title").inner_rml = "<p>" .. utils.xstr(self.strings.NoReqs) .. "</p>"
	self.document:GetElementById("requisitions_count").inner_rml = "<p></p>"
	self.document:GetElementById("requisitions_desc").inner_rml = "<p></p>"
	--self.document:GetElementById("requisitions_requiredcp"):SetClass("hidden", true)
	self.document:GetElementById("requisition_amount_input"):SetClass("hidden", true)
	self.document:GetElementById("submit_cont"):SetClass("hidden", true)
	
end

function RequisitionsController:SelectEntry(key)

	--Find default item data
	local defaultIndex = utils.getTableIndex(backstock.default[selectedData], key)
	local defaultData = backstock.default[selectedData][defaultIndex]
	md.print("REQUISITIONS found " .. key .. " in default table " .. selectedData .. " at index " .. defaultIndex)
	
	--Find save item data
	local saveIndex = utils.getTableIndex(backstock.current[selectedData], key)
	local saveData = backstock.current[selectedData][saveIndex]
	md.print("REQUISITIONS found " .. key .. " in save table " .. selectedData .. " at index " .. saveIndex)
	
	--Find requisitions item data
	local reqIndex = utils.getTableIndex(backstock.current.requisitions[selectedData], key)
	local reqData = backstock.current.requisitions[selectedData][reqIndex]
	md.print("REQUISITIONS found " .. key .. " in requisitions table " .. selectedData .. " at index " .. reqIndex)
	
	--Save current selection in case player submits a requisition!
	self.currentSelection = reqData

	if key ~= self.SelectedEntry and defaultIndex ~= "" then
	
		ScpuiSystem.modelDraw = {}
		ScpuiSystem.modelDraw.draw = true
		ScpuiSystem.modelRot = 40
		local aniWrapper = self.document:GetElementById("requisitions_view")
		aniWrapper:RemoveChild(aniWrapper.first_child)
	
		if self.SelectedEntry then
			local oldEntry = self.document:GetElementById(self.SelectedEntry)
			if oldEntry then oldEntry:SetPseudoClass("checked", false) end
		end
		
		md.print("REQUISITIONS getting id for " .. key)
		local thisEntry = self.document:GetElementById(key)
		self.SelectedEntry = key
		thisEntry:SetPseudoClass("checked", true)
		
		self.currentKey = key
		
		local amountRemaining = backstock.current.requisitions[selectedData][reqIndex].amount
		local amountOwned = backstock.current[selectedData][saveIndex].remaining or 0
		local itemCost = backstock.current.requisitions[selectedData][reqIndex].cost

		self.document:GetElementById("requisitions_title").inner_rml = "<p>" .. defaultData.name .. "</p>"
		self.document:GetElementById("requisitions_owned").inner_rml = "<p>" .. utils.xstr(self.strings.Owned) .. ": " .. amountOwned .. "</p>"
		self.document:GetElementById("requisitions_available").inner_rml = "<p>" .. utils.xstr(self.strings.Available) .. ": " .. amountRemaining .. "</p>"
		self.document:GetElementById("requisitions_cost").inner_rml = "<p>" .. utils.xstr(self.strings.Cost) .. ": " .. itemCost .. " " .. utils.xstr(self.strings.CommandPoints) .. "<br></br>" .. utils.xstr(self.strings.PerItem) .. "</p>"
		
		--Decide if item is a weapon or a ship
		if selectedData == "ships" then
			local thisShipClass = tb.ShipClasses[key]
			
			if self.first_run == false then
				async.run(function()
					async.await(async_util.wait_for(0.001))
					ScpuiSystem.modelDraw.class = key
					ScpuiSystem.modelDraw.element = self.document:GetElementById("requisitions_view")
					self.first_run = true
				end, async.OnFrameExecutor)
			else
				ScpuiSystem.modelDraw.class = key
				ScpuiSystem.modelDraw.element = self.document:GetElementById("requisitions_view")
			end
			
			--Let's convert PowerOutput to something interesting
			local power = math.ceil(thisShipClass.PowerOutput * 10) * 100
			local thisShipPower = power .. utils.xstr(self.strings.PowerSuffix)
			
			--This is the big call that writes all the things. I don't know a better way of doing this while maintaining maximum utility to translate and keep the rml clean.
			self.document:GetElementById("requisitions_desc").inner_rml = "<p>" .. thisShipClass.Description .. "<br></br><br></br>" .. utils.xstr(self.strings.FactionIntro) .. " " .. defaultData.faction .. ".<br></br><br></br>" .. utils.xstr(self.strings.Type) .. ": <span class=\"white\">" .. thisShipClass.TypeString .. "</span><br></br>" .. utils.xstr(self.strings.Maneuver) .. ": <span class=\"white\">" .. thisShipClass.ManeuverabilityString .. "</span><br></br>" .. utils.xstr(self.strings.Armor) .. ": <span class=\"white\">" .. thisShipClass.ArmorString .. "</span><br></br>" .. utils.xstr(self.strings.Manufacturer) .. ": <span class=\"white\">" .. thisShipClass.ManufacturerString .. "</span><br></br>" .. utils.xstr(self.strings.Afterburn) .. ": <span class=\"white\">" .. thisShipClass.AfterburnerFuelMax .. "</span><br></br>" .. utils.xstr(self.strings.Countermeasures) .. ": <span class=\"white\">" .. thisShipClass.CountermeasuresMax .. "</span><br></br>" .. utils.xstr(self.strings.Power) .. ": <span class=\"white\">" .. thisShipPower .. "</span></p>"

		else
			local thisWeaponClass = tb.WeaponClasses[key]
			
			if self.first_run == false then
				async.run(function()
					async.await(async_util.wait_for(0.001))
					ScpuiSystem.modelDraw.class = key
					ScpuiSystem.modelDraw.element = self.document:GetElementById("requisitions_view")
					self.first_run = true
				end, async.OnFrameExecutor)
			else
				ScpuiSystem.modelDraw.class = key
				ScpuiSystem.modelDraw.element = self.document:GetElementById("requisitions_view")
			end
			
			--For weapons lets use the Tech Title instead
			self.document:GetElementById("requisitions_title").inner_rml = "<p>" .. thisWeaponClass.Title .. "</p>"
			
			--Handle custom data
			local thisWeaponCreated = defaultData.creator
			local thisWeaponType = defaultData.category
			local thisWeaponRange = math.floor(thisWeaponClass.Speed * thisWeaponClass.LifeMax) .. " " .. utils.xstr(self.strings.RangeSuffix)
			local thisWeaponSpeed = thisWeaponClass.Speed .. " " .. utils.xstr(self.strings.SpeedSuffix)
			local thisWeaponDamage = thisWeaponClass.Damage .. " " .. utils.xstr(self.strings.DamageSuffix)
			local thisWeaponArmor = math.floor(thisWeaponClass.ArmorFactor * thisWeaponClass.Damage) .. " " .. utils.xstr(self.strings.DamageSuffix)
			local thisWeaponShield = math.floor(thisWeaponClass.ShieldFactor * thisWeaponClass.Damage) .. " " .. utils.xstr(self.strings.DamageSuffix)
			local thisWeaponSubsystem = math.floor(thisWeaponClass.SubsystemFactor * thisWeaponClass.Damage) .. " " .. utils.xstr(self.strings.DamageSuffix)
			local thisWeaponDPS = math.floor(thisWeaponClass.Damage / thisWeaponClass.FireWait) .. " " .. utils.xstr(self.strings.DPSSuffix)
			local thisWeaponCargoSize = "" --Only display this for secondaries
			
			--Handle data only for Secondaries
			if selectedData == "secondaries" then
				thisWeaponCargoSize = utils.xstr(self.strings.CargoSize) .. ": <span class=\"white\">" .. thisWeaponClass.CargoSize .. "</span>"
			end
			
			--This is the big call that writes all the things. I don't know a better way of doing this while maintaining maximum utility to translate and keep the rml clean.
			self.document:GetElementById("requisitions_desc").inner_rml = "<p>" .. thisWeaponClass.Title .. "<br></br><br></br>" .. utils.xstr(self.strings.CreatedByIntro) .. " " .. thisWeaponCreated .. ".<br></br><br></br>" .. utils.xstr(self.strings.Seeking) .. ": <span class=\"white\">" .. thisWeaponType .. "</span><br></br>" .. utils.xstr(self.strings.Range) .. ": <span class=\"white\">" .. thisWeaponRange .. "</span><br></br>" .. utils.xstr(self.strings.Speed) .. ": <span class=\"white\">" .. thisWeaponSpeed .. "</span><br></br>" .. utils.xstr(self.strings.DPS) .. ": <span class=\"white\">" .. thisWeaponDPS .. "</span><br></br>" .. utils.xstr(self.strings.ArmorFactor) .. ": <span class=\"white\">" .. thisWeaponArmor .. "</span><br></br>" .. utils.xstr(self.strings.ShieldFactor) .. ": <span class=\"white\">" .. thisWeaponShield .. "</span><br></br>" .. utils.xstr(self.strings.SubsystemFactor) .. ": <span class=\"white\">" .. thisWeaponSubsystem .. "</span><br></br>" .. thisWeaponCargoSize .. "</p>"
		end

	end	

end

function RequisitionsController:DrawModel()

	if ScpuiSystem.modelDraw and ScpuiSystem.substate == "Requisitions" and ScpuiSystem.modelDraw.draw == true then  --Haaaaaaacks
		local thisObjectClass = nil
		
		if ScpuiSystem.modelDraw.class == nil then return end
		
		if ScpuiSystem.dialogActive == true then
			return
		end
		
		if selectedData == "ships" then
			thisObjectClass = tb.ShipClasses[ScpuiSystem.modelDraw.class]
		else
			thisObjectClass = tb.WeaponClasses[ScpuiSystem.modelDraw.class]
		end
		
		ScpuiSystem.modelRot = ScpuiSystem.modelRot + (7 * ba.getRealFrametime())

		if ScpuiSystem.modelRot >= 100 then
			ScpuiSystem.modelRot = ScpuiSystem.modelRot - 100
		end
		
		local modelView = ScpuiSystem.modelDraw.element
						
		local modelLeft = modelView.offset_left + modelView.parent_node.offset_left + modelView.parent_node.parent_node.offset_left + 25 --This is pretty messy, but it's functional
		local modelTop = modelView.parent_node.offset_top + modelView.parent_node.parent_node.offset_top - 40 --Does not include modelView.offset_top because that element's padding is set for anims also subtracts 7px for funsies
		local modelWidth = modelView.offset_width
		local modelHeight = modelView.offset_height
		
		thisObjectClass:renderTechModel(modelLeft, modelTop, modelLeft + modelWidth, modelTop + modelHeight, ScpuiSystem.modelRot, -15, 0, 1.1)
	end

end

--This really just serves to concatentate a bunch of things for styling and xstrs; makes the script more readable
function RequisitionsController:GenerateDialogText(success, amount)

	local fontChoice = nil
	if ScpuiOptionValues.Font_Multiplier then
		fontChoice = ScpuiSystem:getFontSize()
	else
		fontChoice = 5
	end
	local spanOpen1 = "<span class=\"h1-" .. fontChoice .. "\" style=\"color:grey;margin-left:10%;\">"
	local spanOpen2 = "<span class=\"h2-" .. fontChoice .. "\" style=\"margin-left:5%;\">"
	local spanOpen3 = "<span class=\"h1-" .. fontChoice .. "\" style=\"color:grey;margin-left:5%;\">"
	local spanOpen4 = "<span class=\"h1-" .. fontChoice .. "\" style=\"color:red;margin-left:5%;\">"
	local spanClose = "</span>"
	
	local finalString = ""

	if success then
		--Add number requisitions and how much it cose
		local thisString = spanOpen2 .. utils.xstr(self.strings.SuccessText1) .. " " .. tostring(amount) .. " " .. self.currentSelection.name
		if amount > 1 then
			thisString = thisString .. "s" .. spanClose
		else
			thisString = thisString .. spanClose
		end
		--Add line break and total cost
		local thisString = thisString .. "<br></br>" .. spanOpen1 .. utils.xstr(self.strings.SuccessText2) .. ": " .. self.totalCost .. " " .. utils.xstr(self.strings.CommandPoints) .. spanClose
		
		--Add line break and explainer
		local thisString = thisString .. "<br></br>" .. spanOpen1 .. utils.xstr(self.strings.SuccessText3) .. spanClose
		
		--Add line break and total Command Points remaining
		local thisString = thisString .. "<br></br><br></br><br></br>" .. spanOpen3 .. utils.xstr(self.strings.SuccessText4) .. ": " .. backstock.current.playerCP .. spanClose
		
		finalString = thisString
	else
		--Add warning that requisition failed
		local thisString = "<br></br><br></br>" .. spanOpen4 .. utils.xstr(self.strings.FailureText) .. spanClose
		
		--Add Command Points needed
		local thisString = thisString .. "<br></br><br></br>" .. spanOpen1 .. utils.xstr(self.strings.NeededCP) .. " " .. self.totalCost .. " " .. utils.xstr(self.strings.CommandPoints) .. spanClose
		
		--Add Command Points remaining
		local thisString = thisString .. "<br></br>" .. spanOpen1 .. utils.xstr(self.strings.CurrentCP) .. " " .. backstock.current.playerCP .. " " .. utils.xstr(self.strings.CommandPoints) .. spanClose
		
		finalString = thisString
	end
	return finalString
end
	

--Check if the submitted requisition is possible based on amounts and cost
function RequisitionsController:CheckRequisition(numItems)

	--Continue if submit contains a value, otherwise error prompt
	if numItems > 0 then
		local itemAmount = self.currentSelection.amount
		local itemCost = self.currentSelection.cost
		local itemName = self.currentSelection.name
		local itemFaction = self.currentSelection.faction
		
		--If submitted value is larger than what's available, just offer everything available.
		if numItems > self.currentSelection.amount then
			numItems = self.currentSelection.amount
		end
		
		--Calculate total cost of the Requisition
		self.totalCost = numItems * itemCost
		if self.totalCost > backstock.current.playerCP then
			md.print("REQUISITIONS player didn't have enough CP. Needed " .. self.totalCost .. ", had " .. backstock.current.playerCP)
			self.submittedValue = 0
			self.input_id:SetAttribute("value", "")
			--Send a failure popup
			local text = self:GenerateDialogText(false, numItems)
			local title = "<span style=\"font-size:1.8em;color:#AD7F7F;\">" .. utils.xstr(self.strings.FailureTitle) .. "</span>"
			self:Show(text, title)
			return
		else
			self.submittedValue = 0
			self.input_id:SetAttribute("value", "")
			self:SubmitRequisition(numItems, self.totalCost)
		end

	else
		md.print("REQUISITIONS player submitted an empty value")
		--Send a failure popup
		local fontChoice = nil
		if ScpuiOptionValues.Font_Multiplier then
			fontChoice = ScpuiSystem:getFontSize()
		else
			fontChoice = 5
		end
		local text = "<br></br><br></br><span class=\"h1-" .. fontChoice .. "\" style=\"color:red;margin-left:5%;\">" .. utils.xstr(self.strings.EmptyReturn) .. "</span>"
		local title = "<span class=\"h1-" .. fontChoice .. "\" style=\"color:#AD7F7F;\">" .. utils.xstr(self.strings.FailureTitle) .. "</span>"
		self:Show(text, title)
	end

end

--Here is where we actually subtract the submition from the loaded requisition and then reload the document.
function RequisitionsController:SubmitRequisition(finalAmount, finalCost)
	
	self.currentSelection.amount = self.currentSelection.amount - finalAmount
	backstock.current.playerCP = backstock.current.playerCP - finalCost
	
	inventoryTable = backstock.current[selectedData]
	
	if self:CheckExists(inventoryTable, self.currentSelection.name) then
		for i, v in ipairs(inventoryTable) do
			if v.name == self.currentSelection.name then
				v.remaining = v.remaining + finalAmount
			end
		end
	else
		local index = #inventoryTable
		backstock.current[selectedData][index] = {
			name = self.currentSelection.name,
			amount = finalAmount,
			unlocked = true
		}
	end
	--Send a success popup
	local text = self:GenerateDialogText(true, finalAmount)
	local title = "<span style=\"font-size:1.8em;color:#85AD7F;\">" .. utils.xstr(self.strings.SuccessTitle) .. "</span>"
	self:Show(text, title)
	
	self.recentSection = self.currentSection
	self.recentFaction = self.currentFaction
	self.recentKey = self.currentKey
	
	self:SaveChanges()
	
	--Set var to indicate saved loadouts must not be used
	backstock.updated = true
	
	self:LoadData()
	--self:ChangeSection(self.currentSection)
	self:Refresh()

end

function RequisitionsController:SaveChanges()

	md.print("REQUISITIONS saving data...")

	--Clean the table
	backstock:CleanTable(backstock.current.requisitions.ships)
	backstock:CleanTable(backstock.current.requisitions.primaries)
	backstock:CleanTable(backstock.current.requisitions.secondaries)
	
	backstock:SaveChanges()

end

function RequisitionsController:Show(text, title)
	--Create a simple dialog box with the text and title

	ScpuiSystem.modelDraw.draw = false
	ScpuiSystem.dialogActive = true
	
	local dialog = dialogs.new()
		dialog:title(title)
		dialog:text(text)
		dialog:button(dialogs.BUTTON_TYPE_POSITIVE, utils.xstr(self.strings.Okay), true, self.strings.OkayKeypress)
		dialog:escape(true)
		dialog:show(self.document.context)
		:continueWith(function() 
			ScpuiSystem.modelDraw.draw = true 
			ScpuiSystem.dialogActive = nil
		end)
	-- Route input to our context until the user dismisses the dialog box.
	ui.enableInput(self.document.context)
end

function RequisitionsController:CheckExists(tab, val)

	for i, v in ipairs(tab) do
		if v.name == val then
			return true
		end
	end
	return false

end

--Doesn't currently do anything
function RequisitionsController:InputFocusLost()
	self.inputActive = false
end

function RequisitionsController:SubmitPressed()
	if self.submittedValue then
		self:CheckRequisition(self.submittedValue)
	end
end

function RequisitionsController:InputChange(event)

	--remove all whitespace
	local stringValue = event.parameters.value:gsub("^%s*(.-)%s*$", "%1")
	--sorry, no dots either!
	stringValue = string.gsub(stringValue, "%.", "")

	--If RETURN was not pressed then make sure the input is a number with no spaces. Else save the value, clear the field, and continue.
	if event.parameters.linebreak ~= 1 then
		local value = tonumber(stringValue)
		if type(value) == "number" then
			self.input_id:SetAttribute("value", stringValue)
		else
			--remove the trailing character because it was not a number
			stringValue = stringValue:sub(1, -2)
			self.input_id:SetAttribute("value", stringValue)
		end
		
		local val = self.input_id:GetAttribute("value")
		
		if val == "" then
			val = 0
		else
			val = tonumber(val)
		end
		
		self.submittedValue = val
	else
		submit_id = self.document:GetElementById("submit_btn")
		ui.playElementSound(submit_id, "click")
		md.print("REQUISITIONS got submition for " .. stringValue .. " " .. self.currentSelection.name .. "s from faction " .. self.currentSelection.faction)
		self:CheckRequisition(self.submittedValue)
	end
	
	self:UpdateCost()

end

function RequisitionsController:UpdateCost()
	--Now adjust the visible math
	local val = self.input_id:GetAttribute("value")
	if val == "" then
		val = 0
	else
		val = tonumber(val)
	end
	local visibleValue = val * self.currentSelection.cost
	self.document:GetElementById("requisitions_requiredcp").inner_rml = "<p>" .. utils.xstr(self.strings.Selection) .. ": " .. visibleValue .. " " .. utils.xstr(self.strings.CommandPoints) .. "</p>"
end


function RequisitionsController:InputKeyup(element, event)
end

function RequisitionsController:Exit(element)

    ui.playElementSound(element, "click", "success")
	ScpuiSystem:beginSubstate("Inventory")
	self.document:Close()

end

function RequisitionsController:registerEventHandlers()

end

function RequisitionsController:global_keydown(_, event)
    if event.parameters.key_identifier == rocket.key_identifier.ESCAPE then
        event:StopPropagation()
		ScpuiSystem:beginSubstate("Inventory")
		self.document:Close()
    end
end

function RequisitionsController:unload()
    ScpuiSystem:freeAllModels()
end

engine.addHook("On Frame", function()
	if ScpuiSystem.render == true then
		RequisitionsController:DrawModel()
	end
end, {}, function()
	return false
end)

return RequisitionsController
