#include <lffiles.h>
#include <recarray.h>

#include "ps0713lib.h"
#include "../ca/commesse.h"

                                      ////////////////////////////////
                                      ////    TCOMMESSA_STRING    ////
                                      ////////////////////////////////

//IDLAVORO: metodo che restituisce l'Idlavoro
const TString16 TCommessa_string::idlavoro()
{
  return get(0);
}

//GRUPPO: metodo che restituisce il gruppo
const int TCommessa_string::gruppo()
{
  return get_int(1);
}

//CONTO: metodo che restituisce il conto
const int TCommessa_string::conto()
{
  return get_int(2);
}

//SOTCO: metodo che restituisce il sottoconto
const long TCommessa_string::sotco()
{
  return get_long(3);
}

const TString16 TCommessa_string::contostr()
{
	TString & str = get_tmp_string(24);

	str.format("%d|%d|%ld", gruppo(), conto(), sotco());
  return str;
}


//metodo costruttore
TCommessa_string::TCommessa_string(const char* idlavoro, const int gruppo, const int conto, const long sotco)
{
  add(idlavoro);
  add(gruppo);
  add(conto);
  add(sotco);
}



                                      /////////////////////////
                                      ////    TCOMMESSA    ////
                                      /////////////////////////

//CODICE: metodo che restituisce il codice di ripartizione
const TString8 TCommessa::codice() const
{
  return _codice;
}

//CMSSTR: metodo che restituisce la TToken_string contenente le informazioni di codcms e del conto
const TCommessa_string TCommessa::cmsstr() const
{
  return _commessa;
}

//metodo costruttore
TCommessa::TCommessa(const char* codcms)
{
  TString80  str    = cache().get(LF_COMMESSE, codcms, COMMESSE_CODCONTO);
  const int  gruppo = atoi(str.left(3))  > 0  ? atoi(str.left(3))  : 0;
  const int  conto  = atoi(str.mid(3,3)) > 0  ? atoi(str.mid(3,3)) : 0;
  const long sotco  = atol(str.right(6)) > 0L ? atol(str.right(6)) : 0L;

  TCommessa_string cms(codcms, gruppo, conto, sotco);

  _commessa = cms;
}

                                      //////////////////////////
                                      ////    TVB_RECSET    ////
                                      //////////////////////////

TRecnotype TVB_recset::new_rec(const char* buf)
{
  TToken_string str(256,'\t'); //nuovo record tab separator

  if(buf && *buf)
  {
    bool apici=false;

    for (const char* c = buf; *c ; c++)
    {
      if (*c == '"')
      {
        apici = !apici;
      }
      else
      {
        if (*c == separator())
        {
          if (!apici)
            str << str.separator();
          else
            str << *c;
        }
        else
          str << *c;

      }
    }
  }

  const TRecnotype n = TText_recordset::new_rec(str);

  if (n >= 0)
    row(n).separator(str.separator());
  
  return n;
}


TVB_recset::TVB_recset(const char * fileName, const char s)
           : TCSV_recordset("CSV(,)")
{
	set_separator(s);
  load_file(fileName);
}