#include <fstream>
#include "CSVReader.hpp"
#include "Utility.hpp"

using namespace schneide;

namespace
{
}  // namespace

std::vector<CSVReader::Value> CSVReader::valuesFor(
  std::vector<std::string> strings)
{
  std::vector<CSVReader::Value> result;
  result.reserve(strings.size());
  for (auto const& each : strings)
  {
    result.emplace_back(each);
  }
  return result;
}

CSVReader::File CSVReader::parseFile(std::string const& filename, char delimiter)
{
  std::ifstream file(filename);
  if (!file.good())
    throw std::runtime_error("Unable to open file: " + filename);

  std::string str(
    (std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());

  return parseString(str, delimiter);
}

CSVReader::File CSVReader::parseString(std::string const& content, char delimiter)
{
  auto lines = split(content, {"\r\n", "\n"});
  CSVReader::File result;
  result.reserve(lines.size());

  for (auto const& line : lines)
  {
    auto elements = split(line, delimiter);

    if (!elements.empty())
      result.push_back(valuesFor(elements));
  }
  return result;
}
