evento = {};
VarPosOriginal= {x = 381075.66519277, z = -350696.1185350};
comboyAllyGroup = nil
missionEnded = false

isFollowing1 = false
isFollowing2 = false
isFollowing3 = false
isFollowing4 = false

function clearFile(fileName)	
	
		local fdir = lfs.writedir() .. [[Missions\Campaigns\en\Area18\Status\]] .. fileName

		local f,err = io.open(fdir,"w")
		if not f then
				local errmsg = "Error: Need to create new folder " .. fdir
				trigger.action.outText(errmsg, 10)
				return print(err)
		end
				
		f:close()
end


function getPlayersNamesMission0()
	local Players = coalition.getPlayers(coalition.side.BLUE)	 
	local playerNames = ""
	for i = 1, #Players do		
		playerNames = playerNames .. Players[i]:getName() .. ";"
	end	
	return playerNames
end


function evento:onEvent(event)
	local initiatorAircraft	= "none"
	if event.initiator ~= nil then
		initiatorAircraft = event.initiator:getName()					
	end	

	if (world.event.S_EVENT_LAND == event.id) then		
		local allPlayerNames = getPlayersNamesMission0()
		if string.match(allPlayerNames:gsub("%-", "_"), initiatorAircraft:gsub("%-", "_") .. ";" ) ~= nil then
			setMessageDelayedMission0("Welcome to the Area 18, captain. Please, proceed to the end of the runway where an escort vehicle will guide you to the assigned parking slot", 15, 5, false)						
			setMessageDelayedMission0("(INFO: Go to the very end of the runway, and the escort vehicle will be waiting for you at the last exit on your right side)", 45, 5, true)						
			setSoundDelayedMission0("M0_welcometoarea18.ogg", 5)			
		end
	end
end


world.addEventHandler(evento);	


function isPlayerNearEscort(escortGroup)
	local Players = coalition.getPlayers(coalition.side.BLUE)	 
	local isPlayerInRange = false
	for i = 1, #Players do		
		if getDistanceGroupsMission0(Players[i]:getGroup(), escortGroup)  <= 100 then			
			isPlayerInRange = true
		end
	end	
	
	return isPlayerInRange
end


function setMessageDelayedMission0(text, duration, delaySec, clear)
	timer.scheduleFunction(showMessage, {ptext = text, pduration = duration, pclear = clear}, timer.getTime() + delaySec)
end


function setSoundDelayedMission0(sound, delaySec)
	timer.scheduleFunction(playSound, {psound = sound}, timer.getTime() + delaySec)
end


function showMessage(parameters)
	trigger.action.outText(parameters.ptext, parameters.pduration, parameters.pclear)		
end


function playSound(parameters)
	trigger.action.outSoundForCoalition(coalition.side.BLUE, parameters.psound)		
end


function getDistanceGroupsMission0(group1, group2)	
	-- la distancia devuelta es en Km
	if group1 ~= nil and group1:getUnit(1) ~= nil and group2 ~= nil and group2:getUnit(1) ~= nil then
		local distance = math.abs(((group1:getUnit(1):getPoint().x  - group2:getUnit(1):getPoint().x)^2 + (group1:getUnit(1):getPoint().z  - group2:getUnit(1):getPoint().z)^2)^(0.5))
		--trigger.action.outText("getDistanceGroups: " .. distance, 10)
		return distance
	else
		--trigger.action.outText("getDistanceGroups: infinito", 10)
		return 100000000000000
	end
	
end


function getDistancePointPointMission0(point1, point2)	
	-- la distancia devuelta es en Km
	if point1 ~= nil and point2 ~= nil then
		local distance = math.abs(((point1.x  - point2.x)^2 + (point1.y  - point2.y)^2)^(0.5))
		--trigger.action.outText("distancia entre puntos: " .. distance, 5)
		return distance
	else
		return 100000000000000
	end
	
end


function nearComboy()
	trigger.action.outText("(INFO: Now that you are close to the comboy, you can contact them through 'F10 radio menu --> Comboy...')", 30, true) 
	trigger.action.outText("(INFO: This is only a example of how the 'F10 radio menu' can change to react to the mission status)", 30) 
	trigger.action.outSoundForCoalition(coalition.side.BLUE, "Beep.wav")	
	menuReqSITREC = missionCommands.addCommand('Request SITREP', menuPrinc3, requestSITREP, nil)				
end


function requestSITREP()
	
	setMessageDelayedMission0("[BADGER 7]: Eco 1 1. Badger 7. We have lost our SATCOM terminal and we have two trucks grounded.", 30, 4, true)						
	setMessageDelayedMission0("Can't continue with assistance. Please, send message to command. Need repair to proceed. Out", 30, 4, false)					
	setSoundDelayedMission0("M0_ComboySITREP.ogg", 4)	
	setMessageDelayedMission0("(INFO: Now, check again 'F10 radio menu --> Command...' to transmit SITREP)", 30, 20, false) 	
	menuTransmitSITREP = missionCommands.addCommand('Transmit comboy situation to command', menuPrinc1, transmitSITREP, nil)				
	missionCommands.removeItem(menuReqSITREC)
	
end


function transmitSITREP()	
	setMessageDelayedMission0("[AREA18 COMMAND]: Eco 1 1. Command. Copied. Badger 7 in need for assistance. You can proceed to Shiraz", 30, 5, true)								
	setMessageDelayedMission0("(INFO: good job!!!. Now you can RTB. Use runway 29 for the landing in Shiraz)", 30, 5, false) 
	setSoundDelayedMission0("M0_CommandSendHelp.ogg", 5)	
	missionCommands.removeItem(menuTransmitSITREP)	
	trigger.action.setUserFlag(2, 1)	
end


function setPlayerRouteMission0(playerGroup, tableDestiny)
	if playerGroup ~= nil then
		--trigger.action.outText("setPlayerRouteMission00", 10) 

		local posInicial = playerGroup:getUnit(1):getPoint()
			
		local routePoints = {}		
							
			routePoints[1] = {
								["alt"] = posInicial.y,
                                ["type"] = "Turning Point",
								["action"] = "Turning Point",
								["alt_type"] = "BARO",
                                ["formation_template"] = "",
                                ["ETA"] = 0,
                                ["y"] = posInicial.z,
                                ["x"] = posInicial.x,
								["speed"] = 250,
                                ["ETA_locked"] = false,                                
                                ["speed_locked"] = true,			
								}	
		
			routePoints[2] = {
								["alt"] = tableDestiny.z + 1500,
                                ["type"] = "Turning Point",
								["action"] = "Turning Point",
								["alt_type"] = "BARO",
                                ["formation_template"] = "",
                                ["ETA"] = 0,
                                ["y"] = tableDestiny.y,
                                ["x"] = tableDestiny.x,
								["speed"] = 250,
                                ["ETA_locked"] = false,                                
                                ["speed_locked"] = true,			
								}
							
			
		--trigger.action.markToAll(2, "Destination point", {x = xDestiny, y = 0, z = yDestiny})
		
		
		local _mission = { 
            id = 'Mission', 
            params = { 
				airborne = true,
                route = { 
                    points = routePoints
                }, 
            } 
        }
		
		local _controller = playerGroup:getController();
		Controller.setOption(_controller, AI.Option.Ground.id.ALARM_STATE, AI.Option.Ground.val.ALARM_STATE.RED)
		_controller:setTask(_mission)
		--trigger.action.outText("ruta player asignada", 3)
	end	
end;


function createComboyMission0(PosOriginal, distancia, isOnRoad)
	--trigger.action.outText("createComboy", 3)    
		
		--local nombreJugador = world.getPlayer():getName()		
		--local PosOriginal = Unit.getByName(nombreJugador):getPoint()		 
		--trigger.action.outText("POS x: ".. PosOriginal.x .. "; y: " .. PosOriginal.z, 10) 	
		local xAliados = 0
		local yAliados = 0
		local distance = 0
		local counter = 0
		
		while distance < 50000 and counter < 10 do
			xAliados = PosOriginal.x + math.random(-distancia, distancia)
			yAliados = PosOriginal.z + math.random(-distancia, distancia)
			heading = math.random(259)			
			if (isOnRoad) then
				local offsetx, offsety = land.getClosestPointOnRoads("roads", xAliados, yAliados)
				xAliados = offsetx
				yAliados = offsety
			end	
		
			distance = getDistancePointPointMission0({x = xAliados, y = yAliados}, {x = VarPosOriginal.x, y = VarPosOriginal.z})			
			counter = counter +1 
			--trigger.action.outText("distancia:" .. distance, 5)    
		end
			
		
		
		
		local _groundtype = "M1043 HMMWV Armament" --M113; M1043 HMMWV Armament; M818
		local _groundtype2 = "M818"
		local _country = country.id.USA
		
		nameComboyGroup = "Badger 7"            
            
		local _allydata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["task"] = "",
                                ["uncontrolled"] = false,
                                ["groupId"] = 500 + math.random(1, 1000),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados,
                                        ["x"] = xAliados,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados + 10,
                                        ["x"] = xAliados + 10,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[3] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados + 20,
                                        ["x"] = xAliados + 20,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]  
								[4] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados + 30,
                                        ["x"] = xAliados + 30,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]  
                                }, -- end of ["units"]
                                ["y"] = yAliados,
                                ["x"] = xAliados,
                                ["name"] =  nameComboyGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 124,
                    }
            
                    
			return coalition.addGroup(_country, Group.Category.GROUND, _allydata)     						
end;


function initMission0()

comboyAllyGroup = createComboyMission0(VarPosOriginal, 80000, true)

		trigger.action.outText("[AREA18 COMMAND]: Eco Group. Command. You are ordered to cancel your current mission and copy new orders.", 30) 
		trigger.action.outText("We have lost communication with a supply comboy near Shiraz. You are reassigned to explore the comboy's last position. Search near the area, find the comboy and inform what happened to them.", 30)													
		setSoundDelayedMission0("M0_NewOrders.ogg", 1)
		
		setMessageDelayedMission0("INFO:(F10 radio menu option allows you to perform some dinamic actions like identify units, request help, give them orders, etc.)", 60, 31)
		setMessageDelayedMission0("INFO:(This dinamic actions may vary between different types of missions or even depending on the current situation. Check it from time to time if you don't know how to proceed with your mission)", 60, 31)		
		setMessageDelayedMission0(" ", 60, 31)		
		setMessageDelayedMission0("INFO:(ie: Now, get the comboy last position through 'F10 radio menu --> Command...')", 60, 31)					
			
		setMessageDelayedMission0("(INFO: Check your fuel. If you need to AAR, request tankers through  'F10 radio menu -> Request...')", 30, 120, true)
		setMessageDelayedMission0("(INFO: Take into account that, once requested AAR, it will take the tankers a couple of minutes to arrive to the operation area')", 30, 120, false)					
		setSoundDelayedMission0("Beep.wav", 120)			
end


function getCoordinatesSTRMission0(decLat, decLong)
	local lat1, latF1 = math.modf(decLat)
	local latF2, latF3 = math.modf(latF1 * 60)
	
	
	local long1, longF1 = math.modf(decLong)
	local longF2, longF3 = math.modf(longF1 * 60)
	return {lat = string.format("%02d", lat1) .. "º " .. string.format("%02d",latF2) .. "' " .. string.format("%02d",math.floor(latF3 * 60)) .. "''N", 
					long = string.format("%02d", long1) .. "º " .. string.format("%02d",longF2) .. "' " .. string.format("%02d",math.floor(longF3 * 60)) .. "''E"}
	
end


function activateTankersMission0()
	Group.getByName("tanker1"):activate()
	Group.getByName("tanker2"):activate()
	setMessageDelayedMission0("[AREA18 COMMAND]: Command. Tankers are now in the operation area. Contact them through assigned radio frequencies. Out", 10, 7, true)					
	setMessageDelayedMission0("INFO: There are 2 tankers. Choose the one with 'basquest' or 'boom', depending on the AAR type or your current aircraft)", 20, 15, true)					
	setMessageDelayedMission0("TANKER: ", 45, 15, false)					
	setMessageDelayedMission0("     Arco (basket): TACAN 19X; 253.2Mhz AM ", 45, 15, false)					
	setMessageDelayedMission0("     Texaco (boom): TACAN 18X; 251.5Mhz AM ", 45, 15, false)		
	setSoundDelayedMission0("DELCOMMANDTankersInOperationArea.ogg", 7)		
end


function requestTankersMission0()
	--trigger.action.outText("requestTankersMission0", 10, true) 	
	setMessageDelayedMission0("[AREA18 COMMAND]: Roger that. Tankers are heading to operation area. ETA 2 minutes. Out", 10, 2, true)					
	setSoundDelayedMission0("DELCOMMANDTankersHeading.ogg", 2)
	timer.scheduleFunction(activateTankersMission0, nil, timer.getTime() + 120)	
	missionCommands.removeItem(menuReqTanker)
end


function loadComboyCoordinatesMission0()
	--Aรฑadimos ruta a los aviones flaming cliff 3
	--trigger.action.outText("loadComboyCoordinatesMission0", 10, true) 
			local PosAlly = comboyAllyGroup:getUnit(1):getPoint();
			local DestinationPlayer = {x = PosAlly.x, y = PosAlly.z, z= PosAlly.y}	
	
			local Players = coalition.getPlayers(coalition.side.BLUE)	 
			local isPlayerInRange = false
			for i = 1, #Players do				
				setPlayerRouteMission0(Players[i]:getGroup(), DestinationPlayer)
			end	
	
					
--			setPlayerRouteMission0(Group.getByName("A10a_1"), DestinationPlayer)
--			setPlayerRouteMission0(Group.getByName("A10a_2"), DestinationPlayer)
--			setPlayerRouteMission0(Group.getByName("SU25T_1"), DestinationPlayer)
--			setPlayerRouteMission0(Group.getByName("SU25T_2"), DestinationPlayer)
--			setPlayerRouteMission0(Group.getByName("SU33_1"), DestinationPlayer)
--			setPlayerRouteMission0(Group.getByName("SU33_2"), DestinationPlayer)
--			setPlayerRouteMission0(Group.getByName("F15c_1"), DestinationPlayer)
--			setPlayerRouteMission0(Group.getByName("F15c_2"), DestinationPlayer)			
			
	--Para todos los aviones mostramos latitud y longitud, para que el jugador lo programe en su navegador	
	local lat, long, alt = coord.LOtoLL(PosAlly)
	local coordSTR = getCoordinatesSTRMission0(lat, long)

	setMessageDelayedMission0("[AREA18 COMMAND]: Eco 1 1. Copy following coordinates for last known possition of Badger 7. Out", 30, 2, true)						
	setMessageDelayedMission0(coordSTR.lat .. "     " .. coordSTR.long, 120, 2, false)
	setMessageDelayedMission0("INFO: (If you are using a FC3 aircraft, press 1 (Navigation modes key) two times to load Badger 7 coordinates into a WP)", 30, 2, false)
	setSoundDelayedMission0("M0_CopyFollowCoordinates.ogg", 2)		
	
	--trigger.action.outText("Eco 1 1. Copy following coordinates for last known possition of Badger 7. Out", 30, 2 true)
	--trigger.action.outSoundForCoalition(coalition.side.BLUE, "M0_CopyFollowCoordinates.ogg")
	--trigger.action.outText(coordSTR.lat .. "     " .. coordSTR.long, 120)	
	--trigger.action.outText("INFO: (If you are using a FC3 aircraft, press 1 (Navigation modes key) two times to load Badger 7 coordinates into a WP)", 30)	
end;


function setInitialMenuMission0()

menuPrinc1 = missionCommands.addSubMenu('Command...')
			menuReqCoord = missionCommands.addCommand('Request comboy last coordinates', menuPrinc1, loadComboyCoordinatesMission0, nil)				
menuPrinc2 = missionCommands.addSubMenu('Request...')
			menuReqTanker = missionCommands.addCommand('Request Tanker', menuPrinc2, requestTankersMission0, nil)			
menuPrinc3 = missionCommands.addSubMenu('Comboy...')	
		
end



