--To evaluate the DCS debrief.log, update the campaign status files/OOBs, generate a debriefing and initiate generation of next campaign mission
--Initiated by MissionEnd.lua running from within DCS
------------------------------------------------------------------------------------------------------- 
------------------------------------------------------------------------------------------------------- 
-- Miguel Fichier Revision  Mod35.d
-------------------------------------------------------------------------------------------------------
-- debug01.b EndMission

-- Miguel21 modification M35.d version ScriptsMod
-- Miguel21 modification Mod14 : Versionning
-- Miguel21 modification Mod11.j : Multiplayer

local function AcceptMission()

		repeat
			print("\n\n Night or Day ? : "..daytime)								-- info day or not
			print("\n\nAccept Mission ?:")	
			
			print("a".." - Accept mission")
			print("s".." - Skip mission")
			
			m = tostring(io.read())
			m = string.lower(m)
			
		until m ~= nil and ( m == "a" or m == "s" )
		
		if  m == "s" then
			TaskRefused = true	
			
			return false
		else
			return true
		end
end
----- random seed -----
math.randomseed(tonumber(tostring(os.time()):reverse():sub(1,6)))
math.random(); math.random(); math.random()


--load functions
dofile("Init/conf_mod.lua")



--load mission export files
local logExport = loadfile("MissionEventsLog.lua")()											--mission events log
local scenExport = loadfile("scen_destroyed.lua")()												--destroyed scenery objects
local campExport = loadfile("camp_status.lua")()												--camp_status

versionPackageICM = camp.versionPackageICM

if not versionPackageICM or versionPackageICM == nil then										-- Miguel21 modification M35.d version ScriptsMod
	versionPackageICM = os.getenv('versionPackageICM')											-- Miguel21 modification M35.c version ScriptsMod
end

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

if	camp.mission == 1 then																		--if this was a first campaign mission
	dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_ResetCampaign.lua")				--reset the campaign status files
end

--load status file to be updated
require("Active/oob_ground")																	--load ground oob
require("Init/db_airbases")																		--load db_airbases
require("Active/oob_air")																		--load air oob
require("Active/targetlist")																	--load targetlist
require("Active/clientstats")																	--load clientstats



dofile("Init/conf_mod.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_Functions.lua")


--run log evaluation and status updates
dofile("../../../ScriptsMod."..versionPackageICM.."/DEBRIEF_StatsEvaluation.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_DestroyTarget.lua")												--Mod11.j
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_UpdateTargetlist.lua")


--update campaign time
local elapsed_time = math.floor(events[#events].t - events[1].t)								--mission runtime in seconds
camp.time = camp.time + elapsed_time															--add mission time to campaign time


--create and view debriefing file for mission
dofile("../../../ScriptsMod."..versionPackageICM.."/DEBRIEF_Text.lua")														--In this script the actual text is created. Script loaded after oob modifications above have been made.
local debriefFile = io.open("Debriefing/Debriefing " .. camp.mission .. ".txt", "w")			--create new debriefing file
debriefFile:write(debriefing)																	--write debriefing text into file (variable debriefing comes from DEBRIEF_Text.lua)
debriefFile:close()
os.execute('start "Debriefing" "notepad.exe" "Debriefing/Debriefing ' .. camp.mission .. '.txt"')	--open the debriefing file with notepad

		
if versionPackageICM then
	print("= = = = = = = = = = = = = = = = = = = = Script: "..versionPackageICM.." = = = = = = = = = = = = = = = = = =") 
else 
	print("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =")
end
			
--ask for input to save results and continue with campaign or disregard the last mission
print("\nAccept mission results and continue with campaign? y(es)/n(o):\n")						--ask for user confirmation
local input																						--user input

repeat
	input = io.read()
	input = string.lower(input)
	if input == "y" or input == "yes" or input == "n" or input == "no" then
		break
	else
		print("\n\nInvalid entry. Respond with y(es) or n(o):\n")
	end
until input == "y" or input == "yes" or input == "n" or input == "no"

print("\n\n")

if input == "y" or input == "yes" then
	
	--save new data (remaining files are updated in MAIN_NextMission.lua)
	local client_str = "clientstats = " .. TableSerialization(clientstats, 0)					--make a string
	local clientFile = io.open("Active/clientstats.lua", "w")									--open clientstats file
	clientFile:write(client_str)																--save new data
	clientFile:close()
	
	local oob_scen_old = loadfile("Active/oob_scen.lua")()										--load oob_scen file
	for scen_name,scen in pairs(scen_log) do													--iterate through destroyed scenery objects
		if scen.x and scen.z then																--destroyed scenery object has x and z coordinates
			oob_scen[scen_name] = scen															--add/update to oob_scen
		end
	end
	local scen_str = "oob_scen = " .. TableSerialization(oob_scen, 0)							--make a string
	local scenFile = io.open("Active/oob_scen.lua", "w")										--open oob_scen file
	scenFile:write(scen_str)																	--save new data
	scenFile:close()
	
repeat
	--===================================================================================
	-- Ecran N°1 Choix entre Single ou Multi player
  print("Select :\ns Singleplayer  \nm Multiplayer (In test)")

	choix1 = io.read()
	choix1 = string.lower(choix1)
	
	--===================================================================================
		-- Ecran N°2 Selection Nombre d'avion Flight 1	
   if choix1 == "m"  then
	
		type_flight_02 = "Nothing"
		coopFlag01 = true
		local u_base = ""

		for nSide , nUnit in pairs(oob_air) do
			for m , unit in pairs(nUnit) do
				if   unit.player == true then
					type_flight_01 = unit.type
					u_base = unit.base.." "..unit.name
					idType = m
					side = nSide
				end
			end
		end
		
		
		print("Select number of players on "..type_flight_01.." "..u_base..":\n1 - "..type_flight_01..":\n2 - "..type_flight_01.."\n3 - "..type_flight_01.."\n4 - "..type_flight_01.."\nq(uit)")
		input = tonumber(io.read())

		if  input >= 1 and  input <= 4 then
			coop = tonumber(input)
		else 
			print("\nInvalid entry.\n")
			break
		end

	--===================================================================================
		-- -- Ecran N°3 Selection Task du Flight 1
		-- print("Side: "..side.." Select Type of Task")
		-- print( "0 : Random ")
		-- task = {}
		-- ti = 1
		
		-- for taskStr , nbool in pairs(oob_air[side][idType].tasks) do
			-- if   nbool == true  then
				-- task[ti] = taskStr
				-- print( ti.." : "..tostring(taskStr))
				-- ti = ti+1
			-- end
		-- end
		
		-- input = tonumber(io.read())
		
		-- if  input >= 0 and  input <= ti then
			-- task_flight_01 =  tostring(task[input])
			-- if input == 0 then task_flight_01 = "Random"  end 				
			
		-- else 
			-- print("\nInvalid entry.\n")
			-- break
		-- end

	--===================================================================================
		-- Ecran N°4 Selection Type d'avion du Flight 2
		-- print(task_flight_01)
		print("Select Type of second playable plane:\n q(uit)")
		
		print( "0 : No 2nd Type: ")
		playable_type = {}
		ti = 1 
		for m , unit in pairs(oob_air["blue"]) do
			if   playable_m[unit.type] and unit.inactive ~= true and unit.player ~= true then
				playable_type[ti] = unit.type
				io.write( "\n".. ti.." (blue): "..unit.type..": " ..unit.base .." "..unit.name.."    ")
					for taskStr , nbool in pairs(oob_air["blue"][m].tasks) do
						if   nbool == true  then
							io.write( " ("..tostring(taskStr)..")")
						end
					end
				ti = ti+1
			end
		end
		for m , unit in pairs(oob_air["red"]) do
			if   playable_m[unit.type] and unit.inactive ~= true and unit.player ~= true then
				playable_type[ti] = unit.type
				io.write( "\n".. ti.." (red): "..unit.type..": " ..unit.base .." "..unit.name.."    ")
					for taskStr , nbool in pairs(oob_air["red"][m].tasks) do
						if   nbool == true  then
							io.write( " ("..tostring(taskStr)..")")
						end
					end
				ti = ti+1
			end
		end
		io.write( "\n")
		
		input = io.read()
		input = tonumber(input)

		if input <= (ti ) and input >= 1  then
			type_flight_02 = playable_type[input]
			coopFlag02 = true
		elseif input == 0 then
			type_flight_02 = "Nothing"
		else
			print("\nInvalid entry.\n")
			break
		end
	--===================================================================================
		-- Ecran N°5 Selection Nombre d'avion Flight 2
		if type_flight_02 ~= "Nothing" then
			print("Select number of players on "..type_flight_02.."\n1 - "..type_flight_02.."\n2 - "..type_flight_02.."\n3 - "..type_flight_02.."\n4 - "..type_flight_02.."\nq(uit)")
			input = io.read()
			input = tonumber(input)
			
			coop_flight2 = input
		end

	elseif choix1 == "s" then
	  coop = 1
	elseif choix1 == "q" or choix1 == "quit" then
		break
	else
		print("\nInvalid entry Choix1.\n")
		break
	end





--==========================================================

	--increase campaign mission number
	camp.mission = camp.mission + 1	
	
	--generate next campaign mission
	briefing_status = ""																		--text string to be added to next briefing (status reports are amended for each mission generation attempt until mission is succesfully generated)
	briefing_oob_text_red = ""																	--text string to be added to next briefing (red repair and reinforcements)
	briefing_oob_text_blue = ""																	--text string to be added to next briefing (blue repair and reinforcements)
	PlayerFlight = false																		--variable to control mission generation loop
	
	MissionInstance = 0
	repeat
		print("Generating Next Mission.\n")
	
		MissionInstance = MissionInstance + 1													--count the number of times the mission is generated
		camp.coop = tonumber(coop)															   
		dofile("../../../ScriptsMod."..versionPackageICM.."/MAIN_NextMission.lua")											--generate next mission
		
		if v_EndCampaign then 																	-- debug01.b EndMission
			if AcceptMission() then
				  print("\nEND OF THE CAMPAIGN, SEE THE BRIEFING IN THE MISSION..\n")					-- end of camapaign
				 break
			end
	
		elseif coopFlag02 and MultiPlayerFlight2 then 
			if AcceptMission() then 
				print("\nMission Generated.\n")						--confirmation text
			 break
	   	end
		-- si multijFlight1 demandé et multijFlight1 confirmé, si multijFlight2 refusé, si  tacheFlight1 confirmé
		elseif coopFlag01 and MultiPlayerFlight1 and coopFlag02 ~= true  and taskFlag01  then					
			if AcceptMission() then																		--mission has a player flight
				print("\nMission Generated.\n")						--confirmation text
				break
			end
	 	elseif camp.coop == 1 and PlayerFlight and coopFlag01 ~= true then								--mission has a player flight
				if AcceptMission() then																		--mission has a player flight
			   	print("\nMission Generated.\n")						--confirmation text
			  	 break
		   	end
		elseif stopBug then																			--mission has a player flight
			print("\n\n stopBug .\n")														--confirmation text
			break
		elseif MissionInstance == 50 then														--no player flight could be assigned in 50 tries, stop it
			print("Mission Generation Error. No eligible player flight in 50 attempts. Start a new campaign.\n\n")
			break
		else																					--no player flight could be assigned, advance time and try again
				if playability_criterium.active_unit == nil then
					print("Player unit is not active.\n\n")
				elseif playability_criterium.base == nil then
					print("Player airbase is not operational.\n\n")
				elseif playability_criterium.ready_aircraft == nil then
					print("Player unit has no ready aircraft.\n\n")
				elseif playability_criterium.tot == nil then
					print("Player aircraft type cannot operate at this time of day.\n\n")
				elseif playability_criterium.target == nil then
					print("No eligible mission available for player.\n\n")
				elseif playability_criterium.target_firepower == nil then
					print("Not enough ready aircraft for this mission.\n\n")
				elseif playability_criterium.weather == nil then
					print("Player aircraft type cannot operate in this weather.\n\n")
				elseif playability_criterium.target_range == nil then
					print("No eligible mission available for player.\n\n")
				elseif playability_criterium.coop == nil then
					print("Not enough ready aircraft for all clients.\n\n")
				elseif MultiPlayerFlight1 == false then
					print("Not enough ready aircraft for all clients to 1st Flight.\n\n")
				elseif coopFlag02 == true and MultiPlayerFlight2 == false then
					print("Not enough ready aircraft for all clients to 2nd Flight.\n\n")
				elseif coopFlag01 == true  and type_flight_02 == "Nothing" then
					print("No eligible mission available for 1st Flight.\n\n")													  
				elseif playability_criterium.intercept == nil then
					print("Ground alert intercept duty without launch.\n\n")
				end
		end
		if versionPackageICM then
			print("= = = = = = = = = = = = = = = = = = = = Script: "..versionPackageICM.." = = = = = = = = = = = = = = = = = =") 
		else 
			print("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =")
		end
	until 1 == 2																					--repeat until the next mission is ready (has a player flight)
	break
  until 1 == 2
	os.execute 'pause'
end

--delete mission export files
os.remove("MissionEventsLog.lua")	--DISABLE FOR DEBUG
os.remove("scen_destroyed.lua")		--DISABLE FOR DEBUG
os.remove("camp_status.lua")		--DISABLE FOR DEBUG

os.exit()