Documentation for this module may be created at Module:Damage/doc

local getArgs = require('Module:Arguments').getArgs
local p = {}
function string.starts(String,Start)
    return string.sub(String,1,string.len(Start))==Start
end

function spairs(t)
    local keys = {}
    for k in pairs(t) do keys[#keys+1] = k end
    table.sort(keys)
    local i = 0
    return function()
        i = i + 1
        if keys[i] then
            return keys[i], t[keys[i]]
        end
    end
end

function var(name, dmg)
    return '{{#vardefine:'..name..'|'..dmg..'}}'
end

function p.list(frame)
    local args = getArgs(frame)

    function inArgs(key)
        if args[key] ~= nil then
            return true
        end
    end

    function inArgsStarts(key)
        for k,v in spairs(args) do
            if string.starts(k, key) then
                return true
            end
        end
    end

    local fvals = {}
    local vars = {}
    local traits = {
        heavy = 1.44,
        empowered = 1.2,
        enhanced = 0.8
    }

    if inArgs('empowered') and args.empowered ~= 'true' then
        traits.empowered = args.empowered
    end

    function getTotal(dmg, hits, fval)
        local i = 1
        fvals[fval] = 0
        for k,v in spairs(args) do
            if string.starts(k, 'dmg') then
                fvals[fval] = fvals[fval] + args[dmg .. i] * args[hits .. i]
                i = i + 1
            end
        end
        table.insert(vars, var(fval..'_damage', fvals[fval]))
    end

    -- total/avg
    getTotal('dmg', 'hits', 'total')

    if inArgsStarts('avg_hits') then
        getTotal('dmg', 'avg_hits', 'average')
    end

    -- traits
    if inArgs('useful_penalty') then
        getTotal('dmg', 'hits_useful', 'total_useful')
        table.insert(vars, var('total_damage_useful', fvals.total_useful * args.useful_penalty))
    end

    for k,v in spairs(fvals) do
        for kt,vt in spairs(traits) do
            if inArgs(kt) then
                table.insert(vars, var(k..'_damage_'..kt, v * vt))
            end
        end
    end
    
    return frame:preprocess(table.concat(vars))
end

return p