#pragma once

#include <maps/libs/json/include/value.h>
#include <maps/libs/common/include/exception.h>

#include <boost/lexical_cast.hpp>
#include <string>

namespace maps::wiki::common {

template <typename T>
T readField(const json::Value& value, const std::string& fieldName)
{
    REQUIRE(value.hasField(fieldName), "JSON value has no field " << fieldName);
    return boost::lexical_cast<T>(value[fieldName].toString());
}

template <typename T>
T readOptionalField(
    const json::Value& value,
    const std::string& fieldName,
    const T& defaultValue)
{
    return value.hasField(fieldName)
        ? boost::lexical_cast<T>(value[fieldName].toString())
        : defaultValue;
}

template <class IDType>
std::string
idToJson(IDType id)
{
    static_assert(std::is_integral<IDType>::value, "ID type is not integer number.");
    return std::to_string(id);
}

inline
std::string
sqlDateToJson(const std::string& date)
{
    // 2021-03-01 --> 01.03.2021
    return date.substr(8, 2) + "." + date.substr(5, 2) + "." + date.substr(0, 4);
}

inline
std::string
sqlTimeToJson(const std::string& time)
{
    // 10:00:00+03 --> 10:00
    return time.substr(0, 2) + ":" + time.substr(3, 2);
}

} // maps::wiki:common
