/*
 * 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 "inputcsv.hh"
#include "posutil.hh"
#include "posexcept.hh"
#include "stock.hh"
#include "calibrationrequest.hh"
#include "configuration.hh"

#include <iostream>
#include <unordered_map>

using namespace std ;



/* *** Operations *** */


/**
 * This function fills the current Request from the CSV input file.
 * Blank lines and lines containing only spaces are skipped until a line
 * containing a request is found.
 *
 * @returns `true` if #current_request was correctly filled.
 * @returns `false` in case of error (file not opened, end of file,
 * invalid field or wrong number of fields in the line).
 */
bool InputCSV::fill_current_request()
{
  if (! file.next_line()) // End of file or error
    return false ;
  ++current_line_nb ;

  /* CSV format version */

  uint_fast16_t csv_format_version ;
  if (! read_field(csv_format_version, "the CSV format version"))
    return false ;

  // Check the CSV format
  switch (csv_format_version)
    {
    case 1 :
      // Format 1 is the only one we handle for now.
      break ;
    default :
      cerr << "InputCSV: CSV format version " << csv_format_version
           << " is not handled!\n" ;
      return false ;
    }

  /* Mobile's MAC */

  string mac_mobile ;
  if (! read_field(mac_mobile, "mobile's MAC address"))
    return false ;
  PosUtil::to_upper(mac_mobile) ;

  if (! Configuration::bool_value("positioning.accept-new-mobiles") &&
      ! Stock::mobile_exists(mac_mobile))
    return false ;

  const Mobile &mobile = Stock::find_create_mobile(mac_mobile) ;
  current_request->set_mobile(&mobile) ;

  /* Request type */

  uint_fast8_t type ;
  uint_fast16_t type_r ;
  if (! read_field(type_r, "the request's type"))
    return false ;
  type = type_r ;
  current_request->set_type(type) ;

  /* Number of packets */

  uint_fast16_t nb_packets ;
  if (! read_field(nb_packets, "the number of packets"))
    return false ;
  current_request->set_nb_packets(nb_packets) ;

  /* Timestamp */

  Timestamp timestamp ;
  if (! file.read_timestamp(timestamp))
    {
      // Wrong number of fields
      if (Configuration::is_configured("verbose"))
        cerr << "InputCSV: cannot read the request's timestamp.\n" ;
      return false ;
    }
  current_request->set_time_sent(timestamp) ;

  /* Position */

  Point3D position ;
  if (! file.read_point3d(position))
    {
      // Wrong number of fields
      if (Configuration::is_configured("verbose"))
        cerr << "InputCSV: cannot read the mobile's coordinates.\n" ;
      return false ;
    }

  /* Direction */

  Direction direction ;
  int direction_int ;
  if (! read_field(direction_int, "the mobile's direction"))
    return false ;
  if (direction_int != 0)
    direction = direction_int ;

  /* Read all the {CP_MAC;Packet_ID;SS} */

  unordered_map<string, Measurement> measurements ;

  string mac_cp ;
  while (file.read_field(mac_cp))
    {
      pkt_id_t packet_id ;
      if (! read_field(packet_id, "the packet ID"))
        return false ;

      // Note: the initialisation is useless but avoids a compilation
      // warning.
      int_fast16_t ss = 0 ;
      if (! read_field(ss, "the signal strength"))
        return false ;

      PosUtil::to_upper(mac_cp) ;
      if (! Configuration::bool_value("positioning.accept-new-cps") &&
          ! Stock::cp_exists(mac_cp))
        continue ;

      const CapturePoint &cp = Stock::find_create_cp(mac_cp) ;
      measurements[mac_cp].set_cp(&cp) ;
      measurements[mac_cp].add_ss(packet_id, ss) ;
    }
  if (measurements.empty())
    return false ;
  current_request->set_measurements(measurements) ;

  // Calibration request?
  fill_calibration_request_data(mac_mobile, position, direction, type) ;

  return true ;
}
