---
--- Date         : 2020-07-20 09:53:49
--- Author       : LICHAO7
--- LastEditors  : LICHAO7
--- LastEditTime : 2020-09-28 16:31:48
--- Description  : JSON Wrapper (cjson)
---
JSON = JSON or {};

---
--- Load lua object or table from string.
---
--- @param text string
--- @param default_return any
--- @return any
---
JSON.Loads = function(text, default_return)
    return cjson.decode(text) or default_return;
end

---
--- Load lua object or table from file.
---
--- @param path string
--- @param default_return any
--- @return table
---
JSON.Loadf = function(path, default_return)
    local file = FS.Open(path, "r");
    local tbRetVal = nil;
    if file and file.Valid() then
        -- body
        local text = file.Read();
        file.Close();
        file = nil;
        if not text or #text == 0 then
            return default_return;
        end
        tbRetVal = cjson.decode(text) or default_return;
    else
        LOG_W(string.format("[JSON][Loadf] open file <%s> failed", path));
    end
    return tbRetVal;
end

---
--- Dump table to json string.
---
--- @param content table
--- @return string
---
JSON.Dumps = function(content)
    return cjson.encode(content);
end

---
--- Dump table to json file.
---
--- @param content table
--- @param path string
--- @return boolean
---
JSON.Dumpf = function(content, path)
    local result  = false;
    local file    = nil;
    local jsonstr = cjson.encode(content);
    local fdir    = FS.Path.SplitDir(path);

    if not FS.Path.Exists(fdir) then
        local status, msg = xpcall(FS.MakeDir(fdir), function(e)
            local estr = "Dump table to json file failed, error is create directory failed." .. tostring(e);
            LOG_E("[JSON]" .. estr);
            return estr;
        end);
    end

    if jsonstr then
        file = io.open(path, "w+");
        file:write(jsonstr);
        file:close();
        result = true;
    end
    file   = nil;
    jsonstr = nil;
    return result;
end
