--- @class AssetBundle
--- @field root string Path to the tree root
--- @field files table
local AssetBundle = {
    root = "/assets",
    files = {}
}

--- Loads assets into the tree.
--- Calls [onFileLoading] whenever a file is loaded.
--- @param onFileLoading? fun(path: string): AssetBundle | nil
function AssetBundle:load(onFileLoading)
    local callback = onFileLoading or function(path)
        print("[AssetBundle]: loading " .. path)
    end

    local function enumerate(path)
        local tree = {}

        local contents = love.filesystem.getDirectoryItems(path)
        for _, v in pairs(contents) do
            local newPath = path .. "/" .. v
            local type = love.filesystem.getInfo(newPath).type
            if type == "file" then
                callback(newPath)
                local data = self.loadFile(newPath)
                tree[self.cutExtension(v)] = data
            end
            if type == "directory" then
                tree[v] = enumerate(newPath)
            end
        end

        return tree
    end

    self.files = enumerate(self.root)
    return self
end

function AssetBundle.loadFile(path)
    local filedata = love.filesystem.newFileData(path)
    local ext = filedata:getExtension()
    if (ext == "png") then
        local img = love.graphics.newImage(path)
        img:setFilter("nearest", "nearest")
        return
            img
    elseif (ext == "glsl") then
        return love.graphics.newShader(path);
    elseif (ext == "lua") then
        return require(string.gsub(path, ".lua", ""))
    elseif (ext == "ogg") and string.find(path, "sounds") then
        return love.audio.newSource(path, 'static')
    elseif (ext == "ogg") and string.find(path, "music") then
        return love.audio.newSource(path, 'stream')
    end
    return filedata
end

function AssetBundle.cutExtension(filename)
    return string.match(filename, '(.+)%.(.+)')
end

return AssetBundle
