/*
 * Copyright (c) KylinSoft  Co., Ltd. 2024. All rights reserved.
 *
 * kaiming is licensed under the GPL v2.0+.
 * 
 * See the LICENSE file for more details.
 */

#include "KMDbusJson.h"

/**
 * @brief 将包信息序列化成Json字符串
 *
 * @param name 包名，如 "org.kde.kclock"
 * @param version 包版本，如 "23.04.3"
 * @param size 包大小，如 12363264 字节，开明命令对应 "11.8 MB"
 * @param branch 分支名，如 "stable"
 * @return std::string
 */
std::string KMDbusJson::packLocalInfoToJson(const std::string &name, const std::string &version, const std::string &size, const std::string &branch)
{
    nlohmann::json infoJson;
    infoJson["name"] = name;
    infoJson["version"] = version;
    infoJson["size"] = size;
    infoJson["branch"] = branch;

    return infoJson.dump();
}

std::string KMDbusJson::packProgressInfoToJson(const std::string &refId, int progress, const std::string &speed, int timeout)
{
    nlohmann::json progressInfo;
    progressInfo["refId"] = refId;
    progressInfo["progress"] = progress;
    progressInfo["speed"] = speed;
    progressInfo["timeout"] = timeout;

    return progressInfo.dump();
}

std::string KMDbusJson::packRemoteInfoToJson(const std::string &name, int size, const std::string &branch)
{
    nlohmann::json remoteInfoJson;
    remoteInfoJson["name"] = name;
    remoteInfoJson["size"] = size;
    remoteInfoJson["branch"] = branch;

    return remoteInfoJson.dump();
}

std::string KMDbusJson::errorLocalJson()
{
    nlohmann::json infoJson;
    infoJson["name"] = "";
    infoJson["version"] = "";
    infoJson["size"] = "";
    infoJson["branch"] = "";

    return infoJson.dump();
}

std::string KMDbusJson::parseRemotePathToJson(std::string& stringPath) 
{
    // 分割路径
    std::string::size_type pos = 0;
    std::string token;
    std::vector<std::string> pathParts;

    while ((pos = stringPath.find('/')) != std::string::npos) {
        token = stringPath.substr(0, pos);
        if (!token.empty()) {
            pathParts.push_back(token);
        }
        stringPath.erase(0, pos + 1);
    }

    if (!stringPath.empty()) {
        pathParts.push_back(stringPath);
    }

    nlohmann::json infoJson;
    infoJson["branch"] = pathParts[0];
    infoJson["id"] = pathParts[3];
    infoJson["size"] = pathParts[7];

    return infoJson.dump();
}

std::string KMDbusJson::errorRemoteJson()
{
    nlohmann::json infoJson;
    infoJson["branch"] = "";
    infoJson["id"] = "";
    infoJson["size"] = "";

    return infoJson.dump();
}