util.unit = {}

-- holds a global unitIndex used for naming units
util.unit.unitIndex = 1

--- genreates a unit table out of a unit type table and a starting position table
--- @param typs string[] unit types
--- @param poss table[] unit positions (see DCS vec2)
--- @param headings? table unit headings (mapped to typs). defaults to {0, 0, ...}
--- @param TEMPLATE table template for unit generation (const)
--- @return table
function util.unit.generateUnitTable(typs, poss, headings, TEMPLATE)
    if type(typs) ~= "table" then error(util.error.argErr(typs, "table", 1)) end
    if type(poss) ~= "table" then error(util.error.argErr(poss, "table", 2)) end
    if type(TEMPLATE) ~= "table" then error(util.error.argErr(TEMPLATE, "table", 4)) end

    -- set heading to empty array if not supplied (so we can set all values to 0 later)
    headings = type(headings) == "table" and headings or {}

    local units = {}

    for i, typ in pairs(typs) do
        -- copy the unit template
        local template = util.misc.deepCopy(TEMPLATE)
        
        -- generate the Unit init position (this is done to check for collision)
        local initPos = util.land.getCloseValidPos(poss[i], Unit.getDescByName(typ).box)

        -- populate unit attributes
        template.type = typ
        template.x = initPos.x
        template.y = initPos.y
        template.heading = headings[i] or 0 -- no heading supplied 
        template.name = "mission_unit_" .. tostring(util.unit.unitIndex)

        -- inclement global unit index
        util.unit.unitIndex = util.unit.unitIndex + 1

        -- append units to the unit table
        units[#units + 1] = template
    end

    return units
end