#include <iostream>
#include <thread>
#include "Interactor.hpp"
#include "schneide_base/Logger.hpp"
#include "schneide_base/Utility.hpp"
#include <sstream>

using namespace vera;
using namespace schneide;

namespace
{
}  // namespace

std::string Interactor::question(
  std::string const& what, std::vector<std::string> const& options)
{
  Logger::get()->info("{0} ({1})", what, join(options, "/"));
  return getAnswer(options);
}

void Interactor::say(std::string const& what)
{
  Logger::get()->info(what);
}

void Interactor::wait(std::chrono::duration<double> time)
{
  if (time.count() > 0.0)
    std::this_thread::sleep_for(time);
}

Interactor::Interactor() = default;

std::string Interactor::getAnswer(std::vector<std::string> const& options)
{
  std::string selected;
  
  while (true)
  {
    selected.clear();

    std::getline(std::cin, selected);

    if (!std::cin)
      throw std::runtime_error("Unable to read from cin");

    // Default to first option
    if (selected.empty())
    {
      say(options.front());
      return options.front();
    }

    auto found = std::find(options.begin(), options.end(), selected);
    if (found != options.end())
      break;

    say("Invalid option: {0}", selected);
  }

  return selected;
}
