
--@ module plugin.inline

local plugin_inline={}

local path=require('mypath')
local handlers_render=require('handlers.render')
local filecache=require('filecache')

function plugin_inline.find(env, opts)
    local found={}
    for name, _ in pairs(env.pages) do
        if string.match(name, opts.pattern) then
            table.insert(found, name)
        end
    end
    local function get_created(name)
        local meta=env.pages[name].meta
        return (meta and meta.created_at)
    end
    table.sort(found, function(a, b)
                        local ca=get_created(a)
                        local cb=get_created(b)
                        if not ca then
                            return false
                        elseif not cb then
                            return true
                        else
                            return ca > cb
                        end
                      end)
    
    if not opts.count then
        return found
    else
        local results={}
        for i=1,math.min(opts.count, #found) do
            results[i]=found[i]
        end
        return results
    end
end

function plugin_inline.render(env, opts, pages_)
    local inlinepages={}
    local page=env.page
    local to_root=path.to_root(page.destination)
    
    for i, file in ipairs(pages_) do
        local inlinepage=env.pages[file]
        local relative_location, path_prefix
        
        if opts.absolute then
            location=opts.absolute..inlinepage.destination
            path_prefix=opts.absolute..path.dirname_slash(inlinepage.destination)
        else
            location=path.simplify(to_root..inlinepage.destination)
            path_prefix=path.dirname_slash(location)
        end
        -- clean away index
        if string.match(location, "^index%.[^.]*$") then
            location=""
        else
            location=string.gsub(location, "/index%.[^.]*$", "/")
        end
        
        inlinepages[i]=table.copy(inlinepage)
        -- TODO: env väärin?
        if not opts.no_content then
            inlinepages[i].content=handlers_render.render(file, env, path_prefix)
        end
        inlinepages[i].location=location
    end
    
    local tmplfile=path.join(env.paths.tmpl, opts.template or "inline.template")
    local inline_template=filecache.get(tmplfile)

    local newenv=table.join(env, { inlinepages=inlinepages })
    return handlers_render.process_lua(inline_template, newenv)
end

function plugin_inline.inline(env, opts)
    return plugin_inline.render(env, opts, plugin_inline.find(env, opts))
end

return plugin_inline
