/* common/KMInfoJson.cpp
 *
 * Copyright (C) 2024 OpenKylin, Inc
 */

#include "KMInfoJson.h"
#include <fstream>
#include <filesystem>
#include <regex>
#include <iterator>
#include "KMException.h"
#include "../KMBuilderUtils.h"

namespace fs = std::filesystem;

void KMInfoJson::loadFile(const std::string& jsonFile)
{
    m_root = KMNlohmannJsonHelper::loadFile(jsonFile);
    
    fromJson();
}

void KMInfoJson::saveFile(const std::string& jsonFile)
{
    fs::path baseDir = fs::path(jsonFile).parent_path();
    if (!fs::exists(baseDir))
    {
        std::error_code e;
        if (!KMBuilderUtils::mkpath(baseDir.string(), e))
        {
            throw KMException(e.message());
        }
    }

    toJson();

    std::ofstream o(jsonFile);
    o << std::setw(4) << m_root << std::endl;
}

void KMInfoJson::fromJson()
{
    KMNlohmannJsonHelper helper(m_root);
    id = helper.getStringValue("id");
    archs = helper.getStringListValue("arch");
    base = helper.getStringValue("base");
    runtime = helper.getStringValue("runtime");
    channel = helper.getStringValue("channel");
    commands = helper.getStringListValue("command");
    name = helper.getStringValue("name");
    description = helper.getStringValue("description");
    kind = helper.getStringValue("kind");
    module = helper.getStringValue("module");
    size = helper.getUInt64Value("size");
    version = helper.getStringValue("version");
    envs = helper.getStringMapValue("env");
    permissions = helper.getStringListValue("permission");
    license = helper.getStringValue("license");
    homepage = helper.getStringValue("homepage");
    maintainers = helper.getStringListValue("maintainer");

    // name[zh_CN]
    names = helper.fromPrefix("name[");
    // description[zh_CN]
    descriptions = helper.fromPrefix("description[");

}

void KMInfoJson::toJson()
{
    m_root["id"] = id;
    m_root["base"] = base;
    m_root["runtime"] = runtime;
    
    KMNlohmannJsonHelper helper(m_root);
    helper.setStringValue("channel", channel);
    helper.setStringValue("name", name);
    helper.setStringValue("description", description);
    helper.setStringValue("kind", kind);
    helper.setStringValue("module", module);
    helper.setUInt64Value("size", size);
    helper.setStringValue("version", version);
    helper.setStringValue("license", license);
    helper.setStringValue("homepage", homepage);

    helper.setStringListValue("arch", archs);
    helper.setStringListValue("command", commands);
    helper.add(names);
    helper.add(descriptions);
    helper.setStringMapValue("env", envs);
    helper.setStringListValue("permission", permissions);
    helper.setStringListValue("maintainer", maintainers);
}

