dofilepath("data:scripts/scar/dynaDef.lua")

function SetupOrgSobs()
	CreateDefinitions();

	

	eraImpFighters = {}
	eraRebFighters = {}
	eraBenFighters = {}
	eraVngFighters = {}
	local nextEIF = 1
	local nextERF = 1
	local nextEBF = 1
	local nextEVF = 1
	
	for i, x in Fighters do
		local inEra = 0
		for u, y in x[5] do
			if (y == era) then
				inEra = 1
			end
		end
		if (inEra == 1) then
			if (x[2] == "I") then
				eraImpFighters[nextEIF] = x
				nextEIF = nextEIF + 1
			elseif (x[2] == "R") then
				eraRebFighters[nextERF] = x
				nextERF = nextERF + 1
			elseif (x[2] == "B") then
				eraBenFighters[nextEBF] = x
				nextEBF = nextEBF + 1
			elseif (x[2] == "V") then
				eraVngFighters[nextEVF] = x
				nextEVF = nextEVF + 1
			end
		end
	end

	eraImpBombers = {}
	eraRebBombers = {}
	eraBenBombers = {}
	eraVngBombers = {}
	local nextEIB = 1
	local nextERB = 1
	local nextEBB = 1
	local nextEVB = 1

	for i, x in Bombers do
		local inEra = 0
		for u, y in x[5] do
			if (y == era) then
				inEra = 1
			end
		end
		if (inEra == 1) then
			if (x[2] == "I") then
				eraImpBombers[nextEIB] = x
				nextEIB = nextEIB + 1
			elseif (x[2] == "R") then
				eraRebBombers[nextERB] = x
				nextERB = nextERB + 1
			elseif (x[2] == "B") then
				eraBenBombers[nextEBB] = x
				nextEBB = nextEBB + 1
			elseif (x[2] == "V") then
				eraVngBombers[nextEVB] = x
				nextEVB = nextEVB + 1
			end
		end
	end

	for k, v in Capships do
		SobGroup_Create("OrgAll" .. v[ 1 ])
		SobGroup_Clear("OrgAll" .. v[ 1 ])
	end

	SobGroup_Create("temp");

end

function GetFighterWeighting(Fighter, Side)
	if (Side == "I") then
		for k, v in eraImpFighters do
			if (v[1] == Fighter) then
				return v[6]
			end
		end
	elseif (Side == "R") then
		for k, v in eraRebFighters do
			if (v[1] == Fighter) then
				return v[6]
			end
		end
	elseif (Side == "B") then
		for k, v in eraBenFighters do
			if (v[1] == Fighter) then
				return v[6]
			end
		end
	elseif (Side == "V") then
		for k, v in eraVngFighters do
			if (v[1] == Fighter) then
				return v[6]
			end
		end
	end
	return 0
end

function GetBomberWeighting(Bomber, Side)
	if (Side == "I") then
		for k, v in eraImpBombers do
			if (v[1] == Bomber) then
				return v[6]
			end
		end
	elseif (Side == "R") then
		for k, v in eraRebBombers do
			if (v[1] == Bomber) then
				return v[6]
			end
		end
	elseif (Side == "B") then
		for k, v in eraBenBombers do
			if (v[1] == Bomber) then
				return v[6]
			end
		end
	elseif (Side == "V") then
		for k, v in eraVngBombers do
			if (v[1] == Bomber) then
				return v[6]
			end
		end
	end

end

function FillSob(ShipLong, ShipShort, NextIndex, MFighters, MBombers)
	SobGroup_Create("OrgCurrent");
	SobGroup_Clear("OrgCurrent");
	SobGroup_Create("OrgNew");
	SobGroup_Clear("OrgNew");

	Update_AllShips();

	SobGroup_FillShipsByType("OrgCurrent","AllShips", ShipLong)
	SobGroup_FillSubstract("OrgNew","OrgCurrent","OrgAll" .. ShipShort)

	if (SobGroup_Count("OrgNew") == 0) then
		
	elseif (SobGroup_Count("OrgNew") == 1) then
		SobGroup_Create("Org" .. ShipShort  .. NextIndex)
		SobGroup_Clear("Org" .. ShipShort  .. NextIndex)
		SobGroup_SobGroupAdd("Org" .. ShipShort  .. NextIndex, "OrgNew")
		if (MFighters > 0) then
			SobGroup_Create("Org" .. ShipShort  .. NextIndex .. "Fgt")
			SobGroup_Clear("Org" .. ShipShort  .. NextIndex .. "Fgt")	
		end
		if (MBombers > 0) then
			SobGroup_Create("Org" .. ShipShort  .. NextIndex .. "Bbr")
			SobGroup_Clear("Org" .. ShipShort  .. NextIndex .. "Bbr")	
		end

		setglobal("FM" .. ShipShort .. NextIndex, 7)

		AdvanceIndex(ShipShort)
		SobGroup_SobGroupAdd("OrgAll" .. ShipShort, "OrgNew")
	else
		SobGroup_GetOneFromGroup("temp", "OrgNew")
		if (SobGroup_Count("temp") == 1) then
			SobGroup_Create("Org" .. ShipShort  .. NextIndex)
			SobGroup_Clear("Org" .. ShipShort  .. NextIndex)
			SobGroup_SobGroupAdd("Org" .. ShipShort .. NextIndex, "temp")
			if (MFighters > 0) then
				SobGroup_Create("Org" .. ShipShort .. NextIndex .. "Fgt")
				SobGroup_Clear("Org" .. ShipShort .. NextIndex .. "Fgt")	
			end
			if (MBombers > 0) then
				SobGroup_Create("Org" .. ShipShort .. NextIndex .. "Bbr")
				SobGroup_Clear("Org" .. ShipShort .. NextIndex .. "Bbr")	
			end

			setglobal("FM" .. ShipShort .. NextIndex, 7) 
	
			AdvanceIndex(ShipShort)
			SobGroup_SobGroupAdd("OrgAll" .. ShipShort, "temp")
		else
			Subtitle_Message("ERROR, Several ships of the same type produced in the same frame! (and SobGroup_SplitGroup could not split them)", 10)
		end

	end

	--SobGroup_FillShipsByType("OrgAll" .. ShipShort, "AllShips", ShipLong)
end

function AdvanceIndex(ShipShort)
	for k, v in Capships do
		if (v[ 1 ] == ShipShort) then
			v[ 3 ] = v[ 3 ] + 1
		end
	end
end

-- Runs FillSob on ships, this function should contain all ships with hangars and is run once every frame to make sure all ships are 
-- organized.
function OrgInSobs()
	for k, v in Capships do
		FillSob(v[ 2 ], v[ 1 ], v[ 3 ], v[ 4 ], v[ 5 ])
	end
end

-- Checks all the ships of a particular type if they need to spawn fighters.
-- ShipShort is the reference to what ships should be checked. 
-- ShipIndex is the highest index of this type of ship, get this from the variables in SetupOrgSobs.
function CheckSpawnNeed(ShipShort, ShipIndex, MFighters, MBombers, Side)
	local CurrentIndex
	
	if (ShipIndex > 0) then
		CurrentIndex = 0;
		while (CurrentIndex < ShipIndex) do
			if (SobGroup_Count("Org" .. ShipShort .. CurrentIndex) == 1 and getglobal("FM" .. ShipShort .. CurrentIndex) ~= nil) then

				if (getglobal("FM" .. ShipShort .. CurrentIndex) == 0) then


					if (MFighters > 0) then
						if (SobGroup_Count("Org" .. ShipShort .. CurrentIndex .. "Fgt") == 0) then
							SobGroup_Clear("temp");
							SpawnFighters("Org" .. ShipShort .. CurrentIndex, Side)
	
							SobGroup_DockSobGroupInstant("temp", "Org" .. ShipShort .. CurrentIndex)
							SobGroup_Launch("temp", "Org" .. ShipShort .. CurrentIndex)
							SobGroup_GuardSobGroup("temp", "Org" .. ShipShort .. CurrentIndex)
							SobGroup_SobGroupAdd("Org" .. ShipShort .. CurrentIndex .."Fgt", "temp")
						elseif (SobGroup_Count("Org" .. ShipShort .. CurrentIndex .. "Fgt") <= (6 * MFighters)) then
							local avgHealth = SobGroup_HealthPercentage("Org" .. ShipShort .. CurrentIndex .. "Fgt")
							local fighterCount = SobGroup_Count("Org" .. ShipShort .. CurrentIndex .. "Fgt")
							local squads = fighterCount / (6 * avgHealth)
							--Subtitle_Message("Squads " .. squads, 1)
							if (squads < MFighters) then
								SobGroup_Clear("temp");
								SpawnFighters("Org" .. ShipShort .. CurrentIndex, Side)

								SobGroup_DockSobGroupInstant("temp", "Org" .. ShipShort .. CurrentIndex)
								SobGroup_Launch("temp", "Org" .. ShipShort .. CurrentIndex)
								SobGroup_GuardSobGroup("temp", "Org" .. ShipShort .. CurrentIndex)
								SobGroup_SobGroupAdd("Org" .. ShipShort .. CurrentIndex .."Fgt", "temp")
							end
						end
						if (SobGroup_Count("Org" .. ShipShort .. CurrentIndex .. "Fgt") >= 0) then
							SobGroup_Clear("temp")
							SobGroup_FillProximitySobGroup("temp", "Org" .. ShipShort .. CurrentIndex .. "Fgt", "Org" .. ShipShort .. CurrentIndex, 20000)
							if (SobGroup_Count("temp") == 0) then
								SobGroup_DockSobGroup("temp", "Org" .. ShipShort .. CurrentIndex)
							end
						end
					end

					if (MBombers > 0) then
						if (SobGroup_Count("Org" .. ShipShort .. CurrentIndex .. "Bbr") == 0) then
							SobGroup_Clear("temp");
							SpawnBombers("Org" .. ShipShort .. CurrentIndex, Side)

							SobGroup_DockSobGroupInstant("temp", "Org" .. ShipShort .. CurrentIndex)
							SobGroup_Launch("temp", "Org" .. ShipShort .. CurrentIndex)
							SobGroup_GuardSobGroup("temp", "Org" .. ShipShort .. CurrentIndex)
							SobGroup_SobGroupAdd("Org" .. ShipShort .. CurrentIndex .."Bbr", "temp")
						elseif (SobGroup_Count("Org" .. ShipShort .. CurrentIndex .. "Bbr") <= (6 * MBombers)) then
							local avgHealth = SobGroup_HealthPercentage("Org" .. ShipShort .. CurrentIndex .. "Bbr")
							local fighterCount = SobGroup_Count("Org" .. ShipShort .. CurrentIndex .. "Bbr")
							local squads = fighterCount / (6 * avgHealth)
							--Subtitle_Message("Squads " .. squads, 1)
							if (squads < MBombers) then
								SobGroup_Clear("temp");
								SpawnBombers("Org" .. ShipShort .. CurrentIndex, Side)
	
								SobGroup_DockSobGroupInstant("temp", "Org" .. ShipShort .. CurrentIndex)
								SobGroup_Launch("temp", "Org" .. ShipShort .. CurrentIndex)
								SobGroup_GuardSobGroup("temp", "Org" .. ShipShort .. CurrentIndex)
								SobGroup_SobGroupAdd("Org" .. ShipShort .. CurrentIndex .."Bbr", "temp")
							end
						end
						if (SobGroup_Count("Org" .. ShipShort .. CurrentIndex .. "Bbr") >= 0) then
							SobGroup_Clear("temp")
							SobGroup_FillProximitySobGroup("temp", "Org" .. ShipShort .. CurrentIndex .. "Bbr", "Org" .. ShipShort .. CurrentIndex, 20000)
							if (SobGroup_Count("temp") == 0) then
								SobGroup_DockSobGroup("temp", "Org" .. ShipShort .. CurrentIndex)
							end
						end
					end
				else
					setglobal("FM" .. ShipShort .. CurrentIndex, getglobal("FM" .. ShipShort .. CurrentIndex) - 1)
				end
			end
			CurrentIndex = CurrentIndex + 1
		end		
	end
end

function SpawnFighters(ShipToSpawnIn, Side)
	local possibleFighters = {}
	local nextF = 1

	if (Side == "I") then
		for k, v in eraImpFighters do
			local hasRes = 0
			if (v[4] == "") then
				hasRes = 1
			else
				if (Player_HasResearch(SobGroup_OwnedBy(ShipToSpawnIn), v[4]) == 1) then
					hasRes = 1
				end
			end
			if (hasRes == 1) then
				possibleFighters[nextF] = v[1]
				nextF = nextF + 1
			end
		end
	elseif (Side == "R") then
		for k, v in eraRebFighters do
			local hasRes = 0
			if (v[4] == "") then
				hasRes = 1
			else
				if (Player_HasResearch(SobGroup_OwnedBy(ShipToSpawnIn), v[4]) == 1) then
					hasRes = 1
				end
			end
			if (hasRes == 1) then
				possibleFighters[nextF] = v[1]
				nextF = nextF + 1
			end
		end
	elseif (Side == "B") then
		for k, v in eraBenFighters do
			local hasRes = 0
			if (v[4] == "") then
				hasRes = 1
			else
				if (Player_HasResearch(SobGroup_OwnedBy(ShipToSpawnIn), v[4]) == 1) then
					hasRes = 1
				end
			end
			if (hasRes == 1) then
				possibleFighters[nextF] = v[1]
				nextF = nextF + 1
			end
		end
	elseif (Side == "V") then
		for k, v in eraVngFighters do
			local hasRes = 0
			if (v[4] == "") then
				hasRes = 1
			else
				if (Player_HasResearch(SobGroup_OwnedBy(ShipToSpawnIn), v[4]) == 1) then
					hasRes = 1
				end
			end
			if (hasRes == 1) then
				possibleFighters[nextF] = v[1]
				nextF = nextF + 1
			end
		end
	end

	local totalWeighting = 0
	if (nextF > 1) then
		for x = 1, (nextF - 1), 1 do
			totalWeighting = totalWeighting + GetFighterWeighting(possibleFighters[x], Side)
		end
	end

	if (totalWeighting > 0) then
		local randomNum = random(totalWeighting)
		
		for x = 1, (nextF - 1), 1 do
			randomNum = randomNum - GetFighterWeighting(possibleFighters[x], Side)
			if (randomNum < 1) then
				SpawnFIfPossible(SobGroup_OwnedBy(ShipToSpawnIn), possibleFighters[x], "temp")
				return
			end
		end
		Subtitle_Message("ERROR: Random fighterspawn failed", 5)
		return
	end
end

function SpawnBombers(ShipToSpawnIn, Side)
	local possibleFighters = {}
	local nextF = 1

	if (Side == "I") then
		for k, v in eraImpBombers do
			local hasRes = 0
			if (v[4] == "") then
				hasRes = 1
			else
				if (Player_HasResearch(SobGroup_OwnedBy(ShipToSpawnIn), v[4]) == 1) then
					hasRes = 1
				end
			end
			if (hasRes == 1) then
				possibleFighters[nextF] = v[1]
				nextF = nextF + 1
			end
		end
	elseif (Side == "R") then
		for k, v in eraRebBombers do
			local hasRes = 0
			if (v[4] == "") then
				hasRes = 1
			else
				if (Player_HasResearch(SobGroup_OwnedBy(ShipToSpawnIn), v[4]) == 1) then
					hasRes = 1
				end
			end
			if (hasRes == 1) then
				possibleFighters[nextF] = v[1]
				nextF = nextF + 1
			end
		end
	elseif (Side == "B") then
		for k, v in eraBenBombers do
			local hasRes = 0
			if (v[4] == "") then
				hasRes = 1
			else
				if (Player_HasResearch(SobGroup_OwnedBy(ShipToSpawnIn), v[4]) == 1) then
					hasRes = 1
				end
			end
			if (hasRes == 1) then
				possibleFighters[nextF] = v[1]
				nextF = nextF + 1
			end
		end
	elseif (Side == "V") then
		for k, v in eraVngBombers do
			local hasRes = 0
			if (v[4] == "") then
				hasRes = 1
			else
				if (Player_HasResearch(SobGroup_OwnedBy(ShipToSpawnIn), v[4]) == 1) then
					hasRes = 1
				end
			end
			if (hasRes == 1) then
				possibleFighters[nextF] = v[1]
				nextF = nextF + 1
			end
		end
	end

	local totalWeighting = 0
	if (nextF > 1) then
		for x = 1, (nextF - 1), 1 do
			totalWeighting = totalWeighting + GetBomberWeighting(possibleFighters[x], Side)
		end
	end

	if (totalWeighting > 0) then
		local randomNum = random(totalWeighting)
		
		for x = 1, (nextF - 1), 1 do
			randomNum = randomNum - GetBomberWeighting(possibleFighters[x], Side)
			if (randomNum < 1) then
				SpawnBIfPossible(SobGroup_OwnedBy(ShipToSpawnIn), possibleFighters[x], "temp")
				return
			end
		end
		Subtitle_Message("ERROR: Random bomberspawn failed", 5)
		return
	end
end

function old_SpawnBombers(ShipToSpawnIn, Side)
	local possibleBombers = {}
	local nextB = 1

	for k, v in Bombers do
		if (v[2] == Side) then
			local inEra = 0
			for x, y in v[ 5 ] do
				if (y == era) then
					inEra = 1
				end
			end
			if (inEra == 1) then
				local hasRes = 0
				if (v[4] == "") then
					hasRes = 1
				else
					if (Player_HasResearch(SobGroup_OwnedBy(ShipToSpawnIn), v[4]) == 1) then
						hasRes = 1
					end
				end
				if (hasRes == 1) then
					possibleBombers[nextB] = v[1]
					nextB = nextB + 1
				end
			end
		end
	end

	local totalWeighting = 0
	if (nextB > 1) then
		for x = 1, (nextB - 1), 1 do
			totalWeighting = totalWeighting + GetBomberWeighting(possibleBombers[x])
		end
	end

	if (totalWeighting > 0) then
		local randomNum = random(totalWeighting)
		
		for x = 1, (nextB - 1), 1 do
			randomNum = randomNum - GetBomberWeighting(possibleBombers[x])
			if (randomNum < 1) then
				SpawnBIfPossible(SobGroup_OwnedBy(ShipToSpawnIn), possibleBombers[x], "temp")
				return
			end
		end
		Subtitle_Message("ERROR: Random bomberspawn failed")
		return
	end


	--if (Side == "I") then
	--	SpawnIfPossible(SobGroup_OwnedBy(ShipToSpawnIn), "vgr_tie_bomber", "temp")
	--elseif (Side == "R") then
	--	SpawnIfPossible(SobGroup_OwnedBy(ShipToSpawnIn), "hgn_x_wing", "temp")
	--end
end

function SpawnFIfPossible(Owner, TypeToSpawn, SobToSpawnIn)
	local RUs = Player_GetRU(Owner)

	for k, v in Fighters do
		if (v[1] == TypeToSpawn) then
			if (RUs >= v[3]) then
				SobGroup_SpawnNewShipInSobGroup(Owner, TypeToSpawn, "test", SobToSpawnIn, "StartPos" .. Owner)
				Player_SetRU(Owner, (RUs - v[3]))
				return
			else
				return
			end
		end
	end
	Subtitle_Message("Error in fighterspawn", 5)
end

function SpawnBIfPossible(Owner, TypeToSpawn, SobToSpawnIn)
	local RUs = Player_GetRU(Owner)

	for k, v in Bombers do
		if (v[1] == TypeToSpawn) then
			if (RUs >= v[3]) then
				SobGroup_SpawnNewShipInSobGroup(Owner, TypeToSpawn, "test", SobToSpawnIn, "StartPos" .. Owner)
				Player_SetRU(Owner, (RUs - v[3]))
				return
			else
				return
			end
		end
	end
	Subtitle_Message("Error in bomberspawn", 5)
end

--function SpawnIfPossible(Owner, typeToSpawn, SobToSpawnIn)
--	local RUs = Player_GetRU(Owner)
--
--	for k, v in Fighters do
--		if (v[1] == typeToSpawn) then
--			if (RUs >= v[3]) then
--				SobGroup_SpawnNewShipInSobGroup(Owner, typeToSpawn, "test", SobToSpawnIn, "StartPos" .. Owner)
--				Player_SetRU(Owner, (RUs - v[3]))
--				return
--			end
--		end
---	end
--
--
--
--	if (typeToSpawn == "vgr_tie_fighter") then
--		if (RUs >= 250) then
--			SobGroup_SpawnNewShipInSobGroup(Owner, typeToSpawn, "test", SobToSpawnIn, "StartPos" .. Owner)
--			Player_SetRU(Owner, (RUs - 250))
--		end
--	elseif (typeToSpawn == "vgr_tie_bomber") then
--		if (RUs >= 500) then
--			SobGroup_SpawnNewShipInSobGroup(Owner, typeToSpawn, "test", SobToSpawnIn, "StartPos" .. Owner)
--			Player_SetRU(Owner, (RUs - 500))
--		end
--	elseif (typeToSpawn == "hgn_x_wing") then
--		if (RUs >= 550) then
--			SobGroup_SpawnNewShipInSobGroup(Owner, typeToSpawn, "test", SobToSpawnIn, "StartPos" .. Owner)
--			Player_SetRU(Owner, (RUs - 550))
--		end
--	end
--end

function AddFightersToOrgSubs()
	--randomseed
	--local randomNum = random(2)
	--Subtitle_Message(randomNum,2)

	for k, v in Capships do
		CheckSpawnNeed(v[ 1 ], v[ 3 ], v[ 4 ], v[ 5 ], v[ 6 ])
	end
end

function Update_AllShips()
    local playerIndex = 0
    local playerCount = Universe_PlayerCount()
    SobGroup_Create("AllShips")
    SobGroup_Clear("AllShips")
    while  playerIndex<playerCount do
        SobGroup_SobGroupAdd("AllShips","Player_Ships"..playerIndex)
        playerIndex = playerIndex + 1
    end
end