local super = require "NumberFormatter"

AutoNumberFormatter = super:new()

function AutoNumberFormatter:evaluate(sequence)
    local decimalDigits = 0
    local maxAbs = 0
    sequence:each(function(value)
        if type(value) == 'number' and (value > -math.huge) and (value < math.huge) then
            local value = math.abs(value)
            local intDigits = math.max(math.floor(math.log10(value)), 0) + 1
            local maxFloatDigits = 13 - intDigits
            local decimal = math.fmod(value, 1)
            local scaled = math.floor(0.5 + decimal * 10 ^ maxFloatDigits)
            for digitIndex = maxFloatDigits, 1, -1 do
                if scaled % 10 == 0 then
                    scaled = scaled / 10
                else
                    decimalDigits = math.max(decimalDigits, digitIndex)
                    break
                end
            end
            maxAbs = math.max(maxAbs, value)
        end
    end)
    local formatter
    if maxAbs > 1e-9 then
        formatter = NumberStringFormatter:decimal()
    else
        formatter = NumberStringFormatter:scientific()
        decimalDigits = decimalDigits + math.floor(math.log10(maxAbs))
    end
    return sequence:map(function(value)
        if type(value) == 'number' and (value > -math.huge) and (value < math.huge) then
            if value == 0 then
                return '0'
            else
                return formatter:format(value, decimalDigits)
            end
        end
    end)
end

return AutoNumberFormatter
