--[[
--      simple error collector
--]]
if WOWSHELL_DEBUG_MINIMAP then return end
local max_errors = 5000
local remove_once = 100

for _, a in ipairs{"!Swatter", "!ImprovedErrorFrame", '!BugGrabber', '!!!tekErr'} do
    local _, name, _, enabled = GetAddOnInfo(a)
    if (name and enabled) then
        return
    end
end

local f = CreateFrame'Frame'

local err_table = {}

local insertError = function(msg, stacktrace)
    local err = string.format('%s\n%s\n%s', date'%m/%d/%y %H:%M:%S', msg, stacktrace)

    if(#err_table >= max_errors) then
        for i = 1, remove_once do
            table.remove(err_table, 1)
        end
    end

    table.insert(err_table, err)
end

local errorhandler = function(msg)
    local _, _, stacktrace = string.find(debugstack(1, 50, 50) or "", "[^\n]+\n(.*)")
    insertError(msg, stacktrace)
end

local taint_onevent = function(self, ...)
    local msg = string.join(', ', ...)
    local stacktrace = debugstack(2, 50, 50)
    insertError(msg, stacktrace)
end

function f:PLAYER_LOGIN()
    -- init db
    WS_BUGSACKDB = WS_BUGSACKDB or {}
    local gamever = select(4, GetBuildInfo())

    local dbver = WS_BUGSACKDB.DBVER
    if(not dbver) or (dbver and dbver<gamever) then
        wipe(WS_BUGSACKDB)
        WS_BUGSACKDB.DBVER = gamever
    end

	if (#WS_BUGSACKDB > 50) then
		wipe(WS_BUGSACKDB);
	end

    for k, v in ipairs(err_table) do
        tinsert(WS_BUGSACKDB, v)
    end

    wipe(err_table)
    err_table = WS_BUGSACKDB

    local num_ent = #err_table
    if(num_ent > max_errors) then
        for i = 1, max_errors - num_ent do
            table.remove(err_table, 1)
        end
    end
end

-- register error handler
seterrorhandler(errorhandler)

-- register taint event
f:SetScript('OnEvent', function(self,e,...)
    self[e](self, e,...)
end)

--for _,e in pairs{   'ADDON_ACTION_BLOCKED',
--    'MACRO_ACTION_BLOCKED',
--    'ADDON_ACTION_FORBIDDEN',
--    'MACRO_ACTION_FORBIDDEN',   } do
--    f:RegisterEvent(e)
--    f[e] = taint_onevent
--end

f:RegisterEvent'PLAYER_LOGIN'

