#include "parser.h"

#include <sstream>
#include <stdexcept>

long mixplus::Parser::parseDigit(const std::string& input)
{
    long result = 0;

    for (const char& c : input)
    {
        if (c >= '0' && c <= '9')
        {
            result = result * 10 + (c - '0');
        }
        else
        {
            throw std::invalid_argument("The input string is invalid.");
        }
    }

    return result;
}

long mixplus::Parser::parseHexadecimal(const std::string& input)
{
    long result = 0;

    for (const char& c : input)
    {
        if (c >= '0' && c <= '9')
        {
            result = result * 16 + (c - '0');
        }
        else if (c >= 'a' && c <= 'f')
        {
            result = result * 16 + (c - 'a' + 10);
        }
        else if (c >= 'A' && c <= 'F')
        {
            result = result * 16 + (c - 'A' + 10);
        }
        else
        {
            throw std::invalid_argument("The input string is invalid.");
        }
    }

    return result;
}

long mixplus::Parser::parseNumber(const std::string& input)
{
    if (input.size() > 2 && (input[1] == 'x' || input[1] == 'X'))
    {
        return parseHexadecimal(input.substr(2));
    }

    return parseDigit(input);
}

long mixplus::Parser::parseAndAdd(const int argc, const char** argv)
{
    // 程序名称 first second
    if (argc != 3)
    {
        throw std::invalid_argument("Less arguments is provided.");
    }

    const auto a = std::string(argv[1]);
    const auto b = std::string(argv[2]);

    const auto aValue = parseNumber(a);
    const auto bValue = parseNumber(b);

    return aValue + bValue;
}

Result mixplus::Parser::formatResult(const long value)
{
    std::stringstream ss;
    ss << std::hex;

    ss << "0x";

    // 处理负数：转换为无符号 long，输出补码形式
    if (value < 0)
    {
        ss << static_cast<unsigned long>(value);
    }
    else
    {
        ss << value;
    }

    return Result{
        .hexadecimal = ss.str(), .digit = value
    };
}
