local bretUtils = {
    action_wheel = {},
    request = {},
}

-- Create the initial action wheel.
function bretUtils.action_wheel.init()
    bretUtils.main_action_page = action_wheel:newPage()
    -- Set the default.
    action_wheel:setPage(bretUtils.main_action_page)
    -- Return the page.
    return bretUtils.main_action_page
end

-- Append libraries to the action wheel.
function bretUtils.action_wheel.add(icon, name, page)
    bretUtils.main_action_page:newAction()
        :title(name)
        :item(icon)
        :onLeftClick(function()
            action_wheel:setPage(page)
        end)
end

-- Make it bring the user back to main menu when they click home.
function events.key_press(key, action, modifier)
    if key == 268 then
        action_wheel:setPage(bretUtils.main_action_page)
    end
end

function bretUtils.request.get(url, callback)
    if host:isHost() then
        -- Initialize the request.
        local netRequest = net.http:request(url):method("GET"):send()

        -- Register an event to check if the request is done.
        events.RENDER:register(function()
            -- If it's not then end the event.
            if not netRequest:isDone() then return end
            -- If the code has run this far then it's done.
            local netbody = netRequest:getValue():getData()
            local future = netbody:readAsync(8192)

            -- Remove this event once the first part of the request is done.
            events.RENDER:remove("b1")

            -- Register another event to check if the async reading is done.
            events.RENDER:register(function()
                -- If it's not then end the event.
                if not future:isDone() then return end
                local testString = future:getValue()

                -- Call the callback with the result when it's ready.
                callback(testString)

                -- Clean up events and close the connection.
                events.RENDER:remove("b2")
                netbody:close()
            end, "b2")
        end, "b1")
    end
end

function bretUtils.request.post(url, headers)
    if host:isHost() then
        -- Initialize the request.
        local request = net.http:request(url):method("POST")
        -- Define the headers.
        for key, value in pairs(headers) do
            request:header(key, value)
        end
        -- Send the request.
        request:send()
    end
end

return bretUtils
