local lfs = require "lfs"
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local Share = class("Share")

function Share:initialize(root)
    self._root = root
end

function Share:get_paths(rootpath, paths)
    paths = paths or {}
    for entry in lfs.dir(rootpath) do
        if entry ~= "." and entry ~= ".." then
            local path = string.format("%s/%s", rootpath, entry)

            local attr = lfs.attributes(path)
            assert(type(attr) == "table")

            if attr.mode == "directory" then
                self:get_paths(path, paths)
            else
                -- 获取文件
                entry = entry:match("(.+)%.lua$")
                if entry then
                    paths[entry] = path
                end
            end
        end
    end
    return paths
end

function Share:read_file(fileName)
    local f, errMsg = io.open(fileName, "r")
    if not f then
        return false, errMsg
    end

    local source = f:read("a")
    io.close(f)
    return true, source
end

function Share:load_file(fileName, ...)
    local ok, source = self:read_file(fileName)
    if ok then
        local chunk, err = load(source)
        if "function" == type(chunk) then
            return pcall(chunk, ...)
        else
            return false, err
        end
    else
        local err = source
        return false, err
    end
end

function Share:get_share_data()
    local ret = {}
    if not self._root or "table" ~= type(self._root) then
        return ret
    end

    local files = {}
    for _, rootPath in pairs(self._root) do
        self:get_paths(rootPath, files)
    end
    for fileName, filePath in pairs(files) do
        local ok, data = self:load_file(filePath)
        assert(ok, string.format("%s err: %s", filePath, data))
        ret[fileName] = data
    end
    return ret
end

return Share

