/*
 * This file is part of the Owl Positioning System (OwlPS) project.
 * It is subject to the copyright notice and license terms in the
 * COPYRIGHT.t2t file found in the top-level directory of this
 * distribution and at
 *   https://code.lm7.fr/mcy/owlps/src/master/COPYRIGHT.t2t
 * No part of the OwlPS Project, including this file, may be copied,
 * modified, propagated, or distributed except according to the terms
 * contained in the COPYRIGHT.t2t file; the COPYRIGHT.t2t file must be
 * distributed along with this file, either separately or by replacing
 * this notice by the COPYRIGHT.t2t file's contents.
 */


#include "csvstringreader.hh"
#include "point3d.hh"

#include <iostream>

using namespace std ;
using boost::tokenizer ;
using boost::escaped_list_separator ;
using boost::lexical_cast ;
using boost::bad_lexical_cast ;



/* *** Constructors *** */


CSVStringReader::
CSVStringReader(const std::string &_str, const char _separator):
  separator(_separator), current_token(nullptr), current_field_nb(0)
{
  set_str(_str) ;
}

CSVStringReader::~CSVStringReader()
{
  delete current_token ;
}



/* *** Accessors *** */


/**
 * @returns `false` in case of error (EOF, etc.), `true` else.
 */
void CSVStringReader::set_str(const string &_str)
{
  str = _str ;

  delete current_token ;

  // Split read string into fields (semicolon-separated)
  current_token = new tokenizer<escaped_list_separator<char> >(
    str, escaped_list_separator<char>('\\', separator, '\"')) ;

  token_iterator = current_token->begin() ;
  current_field_nb = 0 ;
}



/* *** Operations *** */


bool CSVStringReader::read_timestamp(Timestamp &t)
{
  string timestamp_str ;
  uint_fast32_t time_s, time_ns ;

  if (! read_field(timestamp_str))
    return false ;

  tokenizer<escaped_list_separator<char> > tok(
    timestamp_str, escaped_list_separator<char>('\\', '.', '\"')) ;
  auto tok_iter = tok.begin() ;

  if (tok_iter == tok.end())
    return false ;
  try
    {
      time_s = lexical_cast<uint_fast32_t>(*tok_iter) ;
    }
  catch (bad_lexical_cast &e)
    {
      print_error_cast() ;
      return false ;
    }
  ++tok_iter ;

  if (tok_iter == tok.end())
    return false ;
  try
    {
      time_ns = lexical_cast<uint_fast32_t>(*tok_iter) ;
    }
  catch (bad_lexical_cast &e)
    {
      print_error_cast() ;
      return false ;
    }

  t = Timestamp(time_s, time_ns) ;

  return true ;
}


/**
 * The first field (X) can start with an opening parenthesis, and the
 * last one (Z) can finish with a closing parenthesis.
 *
 * @param[out] p The variable in which the read Point3D will be stored.
 * It is left untouched if a full Point3D cannot be read successfuly.
 *
 * @returns `true` if the Point3D was read successfuly.
 * @returns `false` in case of error.
 */
bool CSVStringReader::read_point3d(Point3D &p)
{
  float coord[3] ;

  for (unsigned int i = 0 ; i < 3 ; ++i)
    {
      if (token_iterator == current_token->end())
        return false ;
      ++current_field_nb ;

      string field = *token_iterator ;
      if (field.empty())
        return false ;

      /* Handle a leading '(' and a trailing ')' */
      if (i == 0 && field.front() == '(')
        field.erase(field.begin()) ;
      if (i == 2 && field.back() == ')')
        field.pop_back() ;

      try
        {
          coord[i] = lexical_cast<float>(field) ;
        }
      catch (bad_lexical_cast &e)
        {
          print_error_cast() ;
          return false ;
        }

      ++token_iterator ;
    }

  p.set_coordinates(coord) ;
  return true ;
}


void CSVStringReader::print_error_cast() const
{
  cerr
      << "Bad value \"" << *token_iterator
      << "\" at field #" << current_field_nb
      << ", of CSV string \"" << str << "\"!" << endl ;
}
