util.mEvent = {}

util.mEvent.handlers = {}

--- throw a mission event. This event is distributed to all event handlers registerd for this name
--- @param MEName string mission event name
--- @param event table event in the documented structure
--- @return nil
function util.mEvent.throwME(MEName, event)
    if type(MEName) ~= "string" then error(util.error.argErr(MEName, "string", 1)) end
    if type(event) ~= "table" then error(util.error.argErr(event, "table", 2)) end

    local handlers = util.mEvent.handlers[MEName]

    -- no registered handlers
    if handlers == nil then return nil end

    -- inform all registered handlers
    for _i, handler in ipairs(handlers) do
        -- DCS error handling fucks up if an error is thrown in this function => just print it out to console
        local ok, err = util.error.wpcall(function() return handler(event) end)
        if not ok then util.error.raise(err) end
    end

    return nil
end

--- register a mission event handler for a specific event
---
--- WARNING: this function is used for mission based events. NOT the DCS internal events (see DCS world.addEventHandler)
--- @param MEName string mission event name
--- @param func fun(event: table) the function you want to register
--- @return nil
function util.mEvent.registerMEH(MEName, func)
    if type(MEName) ~= "string" then error(util.error.argErr(MEName, "string", 1)) end
    if type(func) ~= "function" then error(util.error.argErr(func, "function", 2)) end

    -- check if this is the first handleer for its kind
    if type(util.mEvent.handlers[MEName]) == "table" then
        local reg = util.mEvent.handlers[MEName]
        reg[#reg+1] = func
    else
        util.mEvent.handlers[MEName] = { [1] = func }
    end

    return nil
end