-- $LastChangedDate: 2010-04-16 22:43:07 -0500 (Fri, 16 Apr 2010) $
-- Dequeue and execute commands from the simulator's command queue.
-- Processing of commands can be extended/hooked using RegisterProcessFunction().
-- See module.txt for documentation and pitfalls.

------------------------
-- CommandQueue class --
------------------------
CommandQueue = {
    cmdString = nil,
    cmdFields = nil,
    processFunctions = { },  -- hook functions
    -- The name of the command is the first element:
    COMMAND_FIELD = 1,
    -- RESTART command field indexs:
    RESTART_FIELD_MISSION  = 2,
    RESTART_FIELD_AIRCRAFT = 3,
    RESTART_FIELD_LOCATION = 4,
    RESTART_FIELD_LAT      = 5,
    RESTART_FIELD_LON      = 6,
    RESTART_FIELD_ALT      = 7,
}

-- Get latest command (as Lua table) or nil.
function CommandQueue:GetCmdFields()
    return self.cmdFields
end

-- Restart mission (see gui.cc).
function CommandQueue:Restart( cmdFields )
    -- Remake player in case the user has chosen a different aircraft using GUI.
    local aircraftName = cmdFields[self.RESTART_FIELD_AIRCRAFT]
    PlayerActor:New( sim.Aircraft.longNameTypeMap[aircraftName] )  -- singleton, nothing returned

    -- Restart mission.
    Mission:Reset()
end

-- Main function to dequeue/execute simulator commands.
function CommandQueue:Process()
    -- Dequeue next command.
    self.cmdString = sim.Program:DequeueCommand()
    if ( self.cmdString ) then  -- if queue not empty
        -- Split command string into fields.
        self.cmdFields = lib.SplitFields( self.cmdString, "," )
        
        -- For each kind of command.
        local cmd = self.cmdFields[1]
        if ( cmd == "RESTART" ) then
            CommandQueue:Restart( self.cmdFields )
        else
            -- Defer unrecognized commands to registered hook functions.
            -- Thus, command processing can be extended externally.
            for func in KEYS(self.processFunctions) do
                func( self.cmdFields )
            end         
        end
    end
end

-- Register a hook function to process a command.
-- Thus, command processing can be extended externally.
-- Func( cmdFieldTable )
function CommandQueue:RegisterProcessFunction( func )
    self.processFunctions[func] = func  -- k=v
end
