--To generate a new mission file. Unzips template mission, defines content of next missions and packs a new mission file
--Initiated by Debrief_Master.lua, BAT_FirstMission.lua or BAT_RedoMission.lua
------------------------------------------------------------------------------------------------------- 
-- last modification M48_g cleanCode_f
if not versionDCE then versionDCE = {} end
versionDCE["MAIN_AcceptMission.lua"] = "1.6.16"
------------------------------------------------------------------------------------------------------- 

-- cleanCode_f						(e: os.remove)
-- adjustment_a						(a: don't load Ini/db_airbase)
-- miguel21 modification M56_a		AssignCallnameSquad
-- miguel21 modification M51_a		Moonphase
-- miguel21 modification M49_a		big central db_loadout
-- miguel21 modification M48_g		Accept result mission (d: garde en memoire le txt camp["briefing_text"]) (g: addImage trigger)(af: debug)
-- -------------------------------------------------------------------------------------------------------

----- unpack template mission file ----
local minizip = require('minizip')

local zipFile = minizip.unzOpen("Init/base_mission.miz", 'rb')

zipFile:unzLocateFile('mission')
local misStr = zipFile:unzReadAllCurrentFile()
local misStrFunc = loadstring(misStr)()

zipFile:unzLocateFile('options')
local optStr = zipFile:unzReadAllCurrentFile()
local optStrFunc = loadstring(optStr)()

zipFile:unzLocateFile('warehouses')
local warStr = zipFile:unzReadAllCurrentFile()
local warStrFunc = loadstring(warStr)()

zipFile:unzLocateFile('l10n/DEFAULT/dictionary')
local dicStr = zipFile:unzReadAllCurrentFile()
local dicStrFunc = loadstring(dicStr)()

zipFile:unzLocateFile('l10n/DEFAULT/mapResource')
local resStr = zipFile:unzReadAllCurrentFile()
local resStrFunc = loadstring(resStr)()

zipFile:unzClose()


----- run scripts to accept content of next mission -----
dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_Data.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_Functions.lua")

-- require("Init/db_loadouts")

require("Active/oob_air")
require("Active/oob_ground")
require("Init/conf_mod")																				-- Miguel21 modification M00 : need option

--retrocompatibilie location radios_freq_compatible file
--recherche en priorité le fichier radios_freq_compatible dans le dossier ScriptsMod puis dans le dossier campagne
local RadioFile = "../../../ScriptsMod."..versionPackageICM.."/radios_freq_compatible.lua"
local TestPath = io.open(RadioFile, "r")																--cette maniere de chercer la presence d un fichier evite un plantage
if TestPath ~= nil then																					--check si le fichier existe dans ScriptsMod
	io.close(TestPath)
	dofile("../../../ScriptsMod."..versionPackageICM.."/radios_freq_compatible.lua")
else	
	local RadioFile2 = "../../../Missions/Campaigns/"..camp.title.."/Init/radios_freq_compatible.lua"
	local TestPath2 = io.open(RadioFile2, "r")
	if TestPath2 ~= nil then																			--check si le fichier exist dans le dossier campagne
		io.close(TestPath2)
		dofile(RadioFile2)
	end
end

local db_airbasesFile = "Active/db_airbases.lua"
local TestPath = io.open(db_airbasesFile, "r")																--cette maniere de chercer la presence d un fichier evite un plantage
if TestPath ~= nil then																					--check si le fichier existe dans ScriptsMod
	io.close(TestPath)
	-- dofile("Active/db_airbases.lua")
else	
	local db_airbasesFile2 = "Init/db_airbases.lua"
	local TestPath2 = io.open(db_airbasesFile2, "r")
	if TestPath2 ~= nil then																			--check si le fichier exist dans le dossier campagne
		io.close(TestPath2)
		dofile(db_airbasesFile2)
		--creer le fichier db_airbases dans Active, meme en cours de campagne, pour garder la retrocompatibilite
		print("MainA create copie db_airbase from Init")
		local airbases_Str = "db_airbases = " .. TableSerialization(db_airbases, 0)
		local trigFile = io.open("Active/db_airbases.lua", "w")
		trigFile:write(airbases_Str)
		trigFile:close()
	end
end


require("Active/targetlist")

require("Active/camp_triggers")

dofile("../../../ScriptsMod."..versionPackageICM.."/DC_Refpoints.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_MissionScore.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_Time.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/UTIL_MoonPhase.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_Weather.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_DestroyTarget.lua")			-- miguel21 Mod26
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_NavalEnvironment.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_UpdateTargetlist.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_CheckTriggers.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_UpdateTargetlist.lua")
dofile("../../../ScriptsMod."..versionPackageICM.."/DC_UpdateOOBGround.lua")

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

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

mission.currentKey = 999999															--not clear how this works but is required for multiplyer clients to be available for selection on mission start

camp.waitingNextGen = true

--si la génération de la mission suivante est repoussée, on sauvegarde le txt crée par les trigger txt precedent
if briefing_text ~= "" then	
	if camp["briefing_text"] then 
		camp["briefing_text"] = FormatDate(camp.date.day, camp.date.month, camp.date.year) .. ", " .. FormatTime(camp.time, "hh:mm") .. camp["briefing_text"] .. ": \\\\n\\\\n" 		--add date and time header
	else 
		camp["briefing_text"] = FormatDate(camp.date.day, camp.date.month, camp.date.year) .. ", " .. FormatTime(camp.time, "hh:mm") .. ": \\\\n\\\\n" 		--add date and time header
	
	end
	
	
	briefing_text = briefing_text:gsub("\\n", "\\\\n")
	briefing_text = briefing_text:gsub("\\\\\n", "\\\\n")
	camp["briefing_text"] = camp["briefing_text"] .. briefing_text

end

--si la génération de la mission suivante est repoussée, on sauvegarde le txt crée par les trigger txt precedent
if BriefingImagesR ~= nil or #BriefingImagesR ~= 0 then	
	if camp["BriefingImagesR"] then 
		table.insert(camp["BriefingImagesR"], BriefingImagesR)
	else 
		camp["BriefingImagesR"]	 = BriefingImagesR
	end
end
if BriefingImagesB ~= nil or #BriefingImagesB ~= 0 then	
	if camp["BriefingImagesB"] then 
		table.insert(camp["BriefingImagesB"], BriefingImagesB)
	else 
		camp["BriefingImagesB"]	 = BriefingImagesB
	end
end


----- convert tables back to strings for insertion into content files -----
local cmpStr = "camp = " .. TableSerialization(camp, 0)

local cmpFile = io.open("Active/camp_status.lua", "w")								--campaign status file
cmpFile:write(cmpStr)
cmpFile:close()

-- ----- remove temporary content files -----
os.remove("misFile.lua")
os.remove("optFile.lua")
os.remove("warFile.lua")
os.remove("dicFile.lua")
os.remove("resFile.lua")
os.remove("GCIdata.lua")
os.remove("aibaseFile.lua")


----- save updated status files  -----
local air_str = "oob_air = " .. TableSerialization(oob_air, 0)								--make a string
if TypeAlias then
	air_str = air_str .. "TypeAlias = " .. TableSerialization(TypeAlias, 0)
end
local airFile = io.open("Active/oob_air.lua", "w")											--open oob air file
airFile:write(air_str)																		--save new data
airFile:close()

local ground_str = "oob_ground = " .. TableSerialization(oob_ground, 0)						--make a string
local groundFile = io.open("Active/oob_ground.lua", "w")									--open oob ground file
groundFile:write(ground_str)																--save new data
groundFile:close()


local tgt_str = "targetlist = " .. TableSerialization(targetlist, 0)						--make a string
local tgtFile = io.open("Active/targetlist.lua", "w")										--open targetlist file
tgtFile:write(tgt_str)																		--save new data
tgtFile:close()

local trigStr = "camp_triggers = " .. TableSerialization(camp_triggers, 0)
local trigFile = io.open("Active/camp_triggers.lua", "w")
trigFile:write(trigStr)
trigFile:close()

local airbases_Str = "db_airbases = " .. TableSerialization(db_airbases, 0)
local trigFile = io.open("Active/db_airbases.lua", "w")
trigFile:write(airbases_Str)
trigFile:close()


-- --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