-- helps the CampaignMaker 
--
------------------------------------------------------------------------------------------------------- 
-- Last Modification M38_k
if not versionDCE then versionDCE = {} end
versionDCE["UTIL_KillTarget.lua"] = "1.4.15"
------------------------------------------------------------------------------------------------------- 
-- Debug_b
-- cleanCode_a
-- miguel21 modification M56_a		AssignCallnameSquad
-- Miguel21 modification M38_k		Check and Help CampaignMaker (k: enleve du targetlist les CAP inter etc)(j: debug) (h: KillTarget step by step)
------------------------------------------------------------------------------------------------------- 

debugKT = true

function killTargetGround(targetName)
	for side_name,side in pairs(oob_ground) do														--side table(red/blue)											
		for country_n,country in pairs(side) do														--country table (number array)
			if country.vehicle then																	--if country has vehicles
				for group_n,group in pairs(country.vehicle.group) do								--groups table (number array)
					if targetName == group.name then
						for unit_n,unit in pairs(group.units) do										--units table (number array)					
							
							print("UKT killTargetGround PasseDestroy "..unit.name)
						
							unit.dead = true														--mark unit as dead in oob_ground
							unit.dead_last = true													--mark unit as died in last mission
						end
					end
				end
			end
			if country.static then																--if country has static objects	
				for group_n,group in pairs(country.static.group) do								--groups table (number array)
					if targetName == group.name then	
						for unit_n,unit in pairs(group.units) do									--units table (number array)
							print("UKT killTargetGround PasseDestroy static "..unit.name)
							
							if unit.dead ~= true then											--unit is not yet dead (some static objects that are spawned in a destroyed state are logged dead at mission start, these must be excluded here)
								group.dead = true												--mark group as dead in oob_ground (static objects can be set as group.dead and spawned in a destroyed state)
								group.hidden = true												--hide dead static object
								unit.dead = true												--mark unit as dead in oob_ground (this is for the targetlist)
								unit.dead_last = true
							end					
						end
					end
				end
			end
			if country.ship then																--if country has ships
				for group_n,group in pairs(country.ship.group) do								--groups table (number array)
					if targetName == group.name then	
						for unit_n,unit in pairs(group.units) do									--units table (number array)
							print("UKT killTargetGround PasseDestroy ship "..unit.name)
							
							unit.dead = true													--mark unit as dead in oob_ground
							unit.dead_last = true												--mark unit as died in last mission
							unit.CheckDay = camp.day                            -- ajoute la date de destruction    Miguel21 modification M19 : Repair SAM   						
						end
					end
				end
			end
		end
	end
end
function killTarget(targetName)
	print("UKT passe 01 targetName "..tostring(targetName))

	killTargetGround(targetName)
	
	for side_name,side in pairs(targetlist) do											--iterate through targetlist
		for target_name,target in pairs(side) do										--iterate through targets
			print("UKT  passe 03 vehicle "..tostring(targetName).." ? "..tostring(target_name))
			if targetName == target_name then	
				print("UKT  passe 04")
				if target.elements  then	--and target.elements[1].x						--if the target has subelements and is a scenery object target (element has x coordinate)
					print("UKT  passe 05")
					for element_n,element in pairs(target.elements) do						--iterate through target elements

						print("UKT PasseDestroy __targetlist__ "..element.name)
						
						killTargetGround(element.name)
						
						if element.dead then											--element was already dead previously
							element.dead_last = false									--mark element as not died in last mission
						else
							element.dead = true	
						end
					end
				end
				print("UKT PasseAlive? target.alive "..target.alive)
				target.alive = 0
				print("UKT PasseAlive2 target.alive2 "..target.alive)
			end
		end
	end
end

if not oob_air or oob_air == nil then
	if FirstMission then
		require("Init/oob_air_init")
	else
		require("Active/oob_air")
	end
end

require("Init/db_airbases")

if not oob_ground or oob_ground == nil then
	require("Active/oob_ground")
end

-- require("Init/conf_mod")

if not targetlist or targetlist == nil then
	if FirstMission then
		require("Active/targetlist")
	else
		require("Init/targetlist_init")
	end
end

if not camp_triggers or camp_triggers == nil then
	if FirstMission then
		require("Active/camp_triggers")
	else
		require("Init/camp_triggers_init")
	end
end

dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_Data.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_Functions.lua")


--===================================================================================
-- Ecran N°0 Choix Num mission
print("Actuel Num de mission "..camp.mission)
print("Change number of mission or press \"Enter\".\n")				--ask for user confirmation

-- local input
-- repeat
	-- input = tonumber(io.read())
	-- if input > 0 and input < 100 then
		-- camp.mission = input
		-- break
	-- else
		-- print("\n\nInvalid entry. Please enter a number:\n")
	-- end
-- until input > 0 and input < 100			

-- camp.mission = input	
	

local input

input = tonumber(io.read())
if input and input ~= nil and input > 0 and input < 100 then
	camp.mission = input
end


repeat
	local tableTargetlist = {}
	local i = 1
	local tableTargetlist = {
			["blue"] = {},
			["red"] = {},
			}
	for side, target_side in pairs(targetlist) do														--iterate through sides in targetlist						
		for target_name, target in pairs(target_side) do												--iterate through all hostile targets
			if target.task and target.task ~= "Intercept" and target.task ~= "CAP" and target.task ~= "AWACS" and target.task ~= "Refueling"  and target.task ~= "Transport" then
				local active = false
				if not target.inactive or target.inactive == nil  then
					active = true
				end
				
				local draftTarget = {
						["name"] = tostring(target_name),
						["priority"] = tonumber(target.priority),
						["alive"] = tonumber(target.alive),
						["active"] = active,
						
						}
				
				table.insert(tableTargetlist[side], draftTarget)						
				
				i = i +1 
			end
		end
	end

	table.sort(tableTargetlist["red"], function(a,b) return a.priority > b.priority  end)
	table.sort(tableTargetlist["blue"], function(a,b) return a.priority > b.priority  end)

	local tabIndex = {}	 
	for side, Targetlist in pairs(tableTargetlist) do
		local jMax
		if side == "red" then
			ownerSide = "blue coalition"
			jMax = #tableTargetlist["red"]
		else
			ownerSide = "red coalition"
			jMax = #tableTargetlist["blue"]
		end
		local j = 1

		local Ckey = 0
		print() print(ownerSide..":")
		for key, value in pairs(Targetlist) do	
			if  j <= jMax  then	
				if side == "red" then
					Ckey = key + #tableTargetlist["blue"]															--permet de n'afficher qu'un nombre continue pour les 2 camps
				else 
					Ckey = key
				end											
				io.write(  Ckey.." "..tostring(value.name) .."  "..tostring(value.alive).." % Actif? "..tostring(value.active).."\n")
				if not tabIndex[Ckey]  then tabIndex[Ckey] = {} end
				tabIndex[Ckey]["side"] = side
				j = j+1	
			end
		end
	end


	repeat
		print("\n(S) Stop script ?")
		inputString = string.lower(io.read())
		if inputString == "s" then
			break
		else
			input = tonumber(inputString)
		end
		-- input = tonumber(io.read())
		if (input == nil or input == "") then input = 999 end
		if input >  #tableTargetlist["blue"] then
			Ckey = input - #tableTargetlist["blue"]
		else
			Ckey = input
		end
		if  tabIndex[input] then
			local side = tabIndex[input]["side"]
			
			killTarget(tableTargetlist[side][Ckey].name)
			
			print("\n"..tableTargetlist[side][Ckey].name.."\n")
		else 
			print("\nInvalid entry.\n")
		end
	until  tabIndex[input] or inputString == "s"
	io.write( "\n")	
	
	dofile("../../../ScriptsMod."..versionPackageICM.."/DC_UpdateTargetlist.lua")							--ce n'est pas un doublon, il faut garder les 2 Update
	dofile("../../../ScriptsMod."..versionPackageICM.."/DC_CheckTriggers.lua")
	-- dofile("../../../ScriptsMod."..versionPackageICM.."/DC_UpdateTargetlist.lua")
	
	-- _affiche(camp.flag, "Marqueur ou  CampFlag")
	
	
	print("(S) Stop script ?")
	print("(enter) to start again.\n")
	input2 = string.lower(io.read())
	
until  input2 == "s"
io.write( "\n")	


--TODO ne permettre que la mise à jour du num mission

	