#include <relapp.h>

#include "batbinl.h"

class TIndici_app : public TRelation_application
{ 
  TRelation* _indici;
  TMask* _maschera;
  
  TString80 _tmp;
  
protected:  
  virtual bool user_create();
  virtual bool user_destroy();
  
  virtual bool changing_mask(int) { return FALSE; }
  virtual TMask* get_mask(int) { return _maschera; }
  virtual TRelation* get_relation() const { return _indici; }

  virtual const char* get_next_key();
  virtual bool save_and_new() const { return TRUE; }

public:
  TIndici_app() {}
  virtual ~TIndici_app() {}  
};

bool TIndici_app::user_create()
{
  _indici = new TRelation(LF_INDLIB);
  _maschera = new TMask("batbinl");
  return TRUE;
}

bool TIndici_app::user_destroy()
{
  delete _maschera;
  delete _indici;
  return TRUE;
}

const char* TIndici_app::get_next_key()
{                  
  const int anno = _maschera->get_int(F_ANNO);
  const TString16 libro = _maschera->get(F_CODLIB);
  if (anno == 0 || libro.empty())
    return "";

  TLocalisamfile index(LF_INDLIB);
  index.zero();
  index.put("ANNO", anno);
  index.put("CODLIB", libro);
  index.put("NUMREG", 9999999L);
  
  long cod = 0;
  int err = index.read(_isgteq);
  switch (err)
  {
  case _iseof:
    index.last();
    err = NOERR;
    break;
  case NOERR:  
    index.prev();
    break;  
  default:
    break;
  }      
  
  if (err == NOERR)
  {
    if (index.get_int("ANNO") == anno && index.get("CODLIB") == libro)
      cod = index.get_long("NUMREG") + 1;    
  }
  
  if (cod > 0)
    _tmp.format("%d|%d|%d|%s|%d|%ld", F_ANNO, anno, F_CODLIB, (const char*)libro, F_INDEX, cod);
  else
    _tmp.cut(0);  

  return _tmp;
}



int ba3900(int argc, char* argv[])
{
  TIndici_app app;
  app.run(argc, argv, "Indici libro unico");
  return 0;
}
