#include "JsonN.h"
#include "common/Utils.h"


static std::string JsonValueToStr(njson& json)
{

}

bool JSON::load(std::string jsonfile, njson& json)
{
    std::ifstream ifs(jsonfile);
    if (!ifs.is_open()) { return false; }
    try { ifs >> json; }
    catch (nlohmann::json::parse_error& e) { return false; }
    return true;
}

bool JSON::parse(std::string jsonstr, njson& json)
{
    try
    {
        if (!jsonstr.empty()) { json = njson::parse(jsonstr); }
    }
    catch (nlohmann::json::parse_error& e)
    {
        std::cout << "JSON parse error: " << e.what() << "\n" << jsonstr << std::endl;
        return false;
    }
    return true;
}

std::string JSON::readStr(njson& json, std::string k)
{
    std::string v;
    try
    {
        if (json.contains(k))
        {
            switch (json[k].type())
            {
            case njson::value_t::string: { v = json[k].get<std::string>(); } break;
            case njson::value_t::boolean: { v = Utils::toStr(json[k].get<bool>()); } break;
            case njson::value_t::number_integer: { v = Utils::toStr(json[k].get<int>()); } break;
            case njson::value_t::number_unsigned: { v = Utils::toStr(json[k].get<int>()); } break;
            case njson::value_t::number_float: { v = Utils::toStr(json[k].get<float>()); } break;
            case njson::value_t::null: {} { v = "null"; } break;
            case njson::value_t::object: {} break;
            case njson::value_t::array: {} break;
            case njson::value_t::binary: {} break;
            case njson::value_t::discarded: {} break;
            default:
                break;
            }

            if (json.is_number()) { v = json.at(k).get<int>(); }
            else if (json.is_string()) { v = json.at(k).get<std::string>(); }
        }
    }
    catch (const nlohmann::detail::exception& e)
    {
        std::cout << "JSON read error: k=" << k << ", err=" << e.what() << std::endl;
    }
    return v;
}

std::string JSON::toStr(njson& json)
{
    std::string v;
    switch (json.type())
    {
    case njson::value_t::string: { v = json.get<std::string>(); } break;
    case njson::value_t::boolean: { v = Utils::toStr(json.get<bool>()); } break;
    case njson::value_t::number_integer: { v = Utils::toStr(json.get<int>()); } break;
    case njson::value_t::number_unsigned: { v = Utils::toStr(json.get<int>()); } break;
    case njson::value_t::number_float: { v = Utils::toStr(json.get<float>()); } break;
    case njson::value_t::null: {} { v = "null"; } break;
    case njson::value_t::object: {} break;
    case njson::value_t::array: {} break;
    case njson::value_t::binary: {} break;
    case njson::value_t::discarded: {} break;
    default:
        break;
    }
    return v;
}


