local GC = select(2, ...)

local Debug = {}
GC.Debug = Debug

local private = {}

-- wow api
local GetChatWindowInfo = GetChatWindowInfo

-- lua api
local type, tostring, string, pairs = type, tostring, string, pairs

function Debug.Log(msg, ...)
    local chatFrame = private.GetDebugChatFrame()
    if chatFrame then GC:Printf(chatFrame, msg, ...) end
end

function Debug.TableToString(t)
    local print_r_cache = {}
    local function sub_print_r(tbl, indent)
        if (print_r_cache[tostring(tbl)]) then
            GC.Debug.Log(indent .. "*" .. tostring(tbl))
        else
            print_r_cache[tostring(tbl)] = true
            if (type(t) == "table") then
                for pos, val in pairs(tbl) do
                    if (type(val) == "table") then
                        GC.Debug.Log(indent .. "[" .. pos .. "] => " ..
                                         tostring(t) .. " {")
                        sub_print_r(val, indent ..
                                        string.rep(" ", string.len(pos) + 8))
                        GC.Debug.Log(indent ..
                                         string.rep(" ", string.len(pos) + 6) ..
                                         "}")
                    elseif (type(val) == "string") then
                        GC.Debug.Log(indent .. "[" .. pos .. '] => "' .. val ..
                                         '"')
                    else
                        GC.Debug.Log(indent .. "[" .. pos .. "] => " ..
                                         tostring(val))
                    end
                end
            else
                GC.Debug.Log(indent .. tostring(t))
            end
        end
    end
    if (type(t) == "table") then
        GC.Debug.Log(tostring(t) .. " {")
        sub_print_r(t, "  ")
        GC.Debug.Log("}")
    else
        sub_print_r(t, "  ")
    end
    GC.Debug.Log("")
end

function private.GetDebugChatFrame() -- private
    local tab = -1
    for i = 1, 10 do
        if GetChatWindowInfo(i) == "LADebug" then
            tab = i
            break
        end
    end

    if (tab ~= -1) then return _G["ChatFrame" .. tab] end
end

