local color = import("color", "local")
local events = import("events", "local")
local messages = {}
local gui, font

events.render += function(layer)
    if #messages == 0 or layer ~= math.huge then
        return
    end
    gui = gui or require("gui")
    font = font or gui.make_font("Verdana")
    local w = 300 * 40 / 20
    local x = _G.gui.window.w - 40 - w
    local y = _G.gui.window.h - 40
    for i = #messages, 1, -1 do
        local message = messages[i]
        local alpha = 1
        if clock() - message[3] > 3 then
            alpha = 1 - (clock() - message[3] - 3) / 2
        end
        if alpha <= 0 then
            table.remove(messages, i)
            break
        end

        local header_size = 20 * 40 / 20
        local small_size = 14 * 40 / 20
        while font:area(tostring(message[1]:upper()), header_size/100) > w - 40 * 2 do
            header_size = header_size - 1
        end

        local this_h = (message[2] and (header_size + small_size + 40 + 3) or header_size) + 40 * 2

        y -= this_h

        gui.rectangle(x - 2, y - 2, w + 4, this_h + 4, color.GUI.window_sidebar)
        gui.rectangle(x, y, w, this_h, color.GUI.window_background)

        font:draw(tostring(message[1]:upper()), x + 40, y + 40, color.GUI.text_hl, header_size/100)

        if message[2] then
            local lines = { tostring(message[2]) }
            local msg_w, msg_h = font:area(lines[1], small_size/100)
            while msg_w > w - 40 * 2 do
                msg_w = 0
                for idx = 1, #lines do
                    local line = lines[idx]
                    local l_w = font:area(line, small_size/100)
                    if l_w > w - 40 * 2 then
                        local last_word = line:sub(-line:reverse():find(" "))
                        if lines[idx + 1] then
                            lines[idx + 1] = last_word .. lines[idx + 1]
                        else
                            lines[idx + 1] = last_word
                        end
                        lines[idx] = line:sub(1, -last_word:len() - 1)
                    end
                    msg_w = math.max(msg_w, font:area(lines[1], small_size/100))
                end
            end

            local y_center = y + this_h - 40 - msg_h * #lines
            for idx = 1, #lines do
                font:draw(lines[idx]:gsub("^ ", ""), x + 40, y_center + (idx - 1) * msg_h, color.GUI.text_hl, small_size/100)
            end
        end

        if i > 1 then
            y = y - 40
        end
    end
end

return {
    new = function(message1, message2)
        table.insert(messages, {message1, message2, clock()})
        if #messages > 1 then
            if messages[#messages][3] == messages[#messages-1][3] then
                messages[#messages][3] = messages[#messages][3] + 0.25
            end
        end
    end,
}