#include "KMRunnerOptions.h"

#include "common/KMLogger.h"
#include "common/KMUtil.h"

class KMRunnerOptions::Private
{
public:
    bool isHelp;
    bool isDevel;
    bool isFileWarding;
    std::string command;
    std::string ref;
    std::vector<std::string> args;
};

KMRunnerOptions::KMRunnerOptions()
    : d_ptr(std::make_shared<Private>())
{
}

void KMRunnerOptions::preParseHook()
{
    addOptions();
}

/**
 * @brief 命令行参数解析后操作
 */
void KMRunnerOptions::postParseHook()
{
    checkOptions(m_varsMap);
    if (d_ptr->isHelp)
    {
        showUsage();
        exit(EXIT_SUCCESS);
    }
}

/**
 * @brief 命令行参数添加描述选项
 */
void KMRunnerOptions::addOptions()
{
    m_optionsDescription = std::make_unique<opt::options_description>(_("\n说明:\n \tkaiming run [OPTION…] ref args - 运行已安装的应用"));

    opt::options_description helpOptions(_("帮助选项"));
    helpOptions.add_options()("help,h", _("显示帮助选项"));
    helpOptions.add_options()("devel,d", _("使用开发运行时"));
    helpOptions.add_options()("file-forwarding", _("启用文件转发"));
    helpOptions.add_options()("command=value", opt::value<string>(&d_ptr->command), _("显示运行命令"));

    opt::options_description positionalOptions(_("选项说明"));
    positionalOptions.add_options()("ref", opt::value<string>(&d_ptr->ref),
                                    _("ref 支持类型:\nid \nid/version \nid/version/module \nid/version/module/channel"))("args", opt::value<vector<string>>(&d_ptr->args), _("command 参数\n"));

    m_optionsDescription->add(helpOptions).add(positionalOptions);
    m_optionsPositionalDescription->add("ref", 1);
    m_optionsPositionalDescription->add("args", -1);
}

/**
 * @brief 命令行参数检查项
 * @param varsMap 存储命令行参数
 */
void KMRunnerOptions::checkOptions(const opt::variables_map &varsMap)
{
    checkOption(varsMap, "help", "h", d_ptr->isHelp);
    checkOption(varsMap, "devel", "d", d_ptr->isDevel);
    checkOption(varsMap, "file-forwarding", "f", d_ptr->isFileWarding);
}

/**
 * @brief 获取命令行command参数
 *  @return 应用要求
 */
std::string KMRunnerOptions::getCommand()
{
    return d_ptr->command;
}

/**
 * @brief 获取命令行要运行的应用程序及相关参数的内容
 */
std::string KMRunnerOptions::getAppId()
{
    return d_ptr->ref;
}

/**
 * @brief 获取启动参数
 * @return vector<string> 返回启动参数
 */
std::vector<std::string> KMRunnerOptions::getArgs()
{
    return d_ptr->args;
}

/**
 * @brief 获取devel开发运行时
 * @return bool true 开发运行时, false 非开发运行时
 */
bool KMRunnerOptions::isDevel()
{
    return d_ptr->isDevel;
}

/**
 * @brief 获取是否启动文件转发
 * @return bool true 启动, false 不启动
 */
bool KMRunnerOptions::isFileWarding()
{
    return d_ptr->isFileWarding;
}
