login

local http = require "http"

local App = {}
App.__index = App

function App:add_route(method, pattern, callback)
    table.insert(self.routes, {method, pattern, callback})
end

function App:run(port)
    self.server:run(port)
end

function App:mount(prefix, app)
    if prefix:sub(#prefix) ~= "/" then
        prefix = prefix .. "/"
    end
    table.insert(self.mounts, {prefix, app})
end

local function new_app(routes)
    local obj = setmetatable({}, App)
    obj.routes = routes or {}
    obj.mounts = {}
    obj.server = http.new_http()
    function obj.server:process(req)
        for i, mount in ipairs(obj.mounts) do
            local prefix, app = unpack(mount)
            if (req.path.."/"):sub(1, #prefix) == prefix then
                req.path = req.path:sub(#prefix)
                return app.server:process(req)
            end
        end
        for i, route in ipairs(obj.routes) do
            local method, pattern, func = unpack(route)
            if req.method == method then
                local params = {req.path:match("^"..pattern.."$")}
                if #params > 0 then
                    return func(req, unpack(params))
                end
            end
        end
        return "nothing here", 404, "Not found"
    end
    return obj
end

return {new_app=new_app}