#include "TextualValue.hpp"
#include "Utility.hpp"

using namespace schneide;

double TextualValue::asDouble() const
{
  try
  {
    std::size_t index = 0;
    auto result = std::stod(mContent, &index);

    if (index != mContent.size())
    {
      throw std::runtime_error("\"" + mContent + "\" is not a number");
    }

    return result;
  }
  catch (std::invalid_argument const&)
  {
    throw std::invalid_argument(
      "Unable to convert \"" + mContent + "\" to a double");
  }
}

int TextualValue::asInteger() const
{
  try
  {
    std::size_t index = 0;
    auto result = std::stoi(mContent, &index);

    if (index != mContent.size())
    {
      throw std::runtime_error("\"" + mContent + "\" is not a number");
    }

    return result;
  }
  catch (std::invalid_argument const&)
  {
    throw std::invalid_argument(
      "Unable to convert \"" + mContent + "\" to an integer");
  }
}

bool TextualValue::asBool() const
{
  for (auto const& each : {"true", "yes", "on", "1"})
    if (each == mContent)
      return true;

  for (auto const& each : {"false", "no", "off", "0"})
    if (each == mContent)
      return false;

  throw std::invalid_argument("Invalid boolean: " + mContent);
}
