#include "cg0201.h"

#include <clifo.h>
#include <indsp.h>

// Definizione dei metodi relativi alla classe TClifoVI

TClifoVI::TClifoVI():TRelation(LF_CLIFO), _oldindirizzi(0), _gesven(FALSE)
{
  add(LF_CFVEN,"TIPOCF=TIPOCF|CODCF=CODCF");
  add(LF_INDSP,"TIPOCF=TIPOCF|CODCF=CODCF");
}

void TClifoVI::destroy_rows()
{
  _indirizzi.destroy();
}

TRectype& TClifoVI::indirizzo(int i)
{
  TRectype *r=(TRectype*)_indirizzi.objptr(i);

  if (r == NULL)
  {
    r = new TRectype(LF_INDSP);
    _indirizzi.add(r,i);
  }
  return *r;
}

int TClifoVI::read_indirizzi()
{
  destroy_rows();
  if (_gesven)
  {
    const TLocalisamfile& rind = lfile(LF_INDSP);
    for (bool ok=is_first_match(LF_INDSP); ok; ok=next_match(LF_INDSP))
    {
      const int nriga=rind.get_int(IND_CODIND) -1;
      indirizzo(nriga)=rind.curr();
    }
    _oldindirizzi=indirizzi_items();
  }  
  return NOERR;
}

int TClifoVI::read(TIsamop op, TReclock lockop, TDate& atdate)
{
  int err = file().read(op,lockop,atdate);
  position_rels();

  if (err == NOERR) 
    read_indirizzi();
  return err;
}

int TClifoVI::write_rec(bool re, const TRectype& rec, TLocalisamfile& f)
{
  if (re)
  {
    const bool scrivi= (f.rewrite(rec)!=NOERR);
    if (scrivi) f.write(rec);
  } else
    f.write(rec);
  return f.status();
}

int TClifoVI::cancella(TLocalisamfile& f, int da, int a)
{
  const char tipocf=lfile().get(IND_TIPOCF)[0];
  const long codcf=lfile().get_long(IND_CODCF);

  for (int i=da; i<=a;i++)
  {
    f.zero();
    f.put(IND_TIPOCF,tipocf);
    f.put(IND_CODCF,codcf);
    f.put(IND_CODIND,i);
    if (f.read(_isequal,_lock)==NOERR)
      f.remove();
  }
  return f.status();
}

int TClifoVI::registra(bool re, bool force)
{
  TLocalisamfile& c=lfile(LF_CLIFO);
  int err=write_rec(re,c.curr(),c);
  if (err!=NOERR) return err;

  // Put here gest_vend() discrimination
  if (_gesven)
  {
    TLocalisamfile& v = lfile(LF_CFVEN);
    err = write_rec(TRUE,v.curr(),v);
    if (err!=NOERR) return err;

    TLocalisamfile& rind=lfile(LF_INDSP);
    const char tipocf=c.get(CLI_TIPOCF)[0];
    const long codcf=c.get_long(CLI_CODCF);

    for (int i=0; i<indirizzi_items(); i++)
    {
      if (!re)
      {
        indirizzo(i).put(IND_TIPOCF,tipocf);
        indirizzo(i).put(IND_CODCF,codcf);
      }
      err=write_rec(TRUE,indirizzo(i),rind);
    }
    if (i<_oldindirizzi)
      cancella(rind,i+1,_oldindirizzi);
    _oldindirizzi=indirizzi_items();
  }
  //  END of gest_vend() discrimination
  return err;
}

int TClifoVI::write(bool force, TDate&)
{
  _oldindirizzi=0;
  return registra(FALSE,force);
}

int TClifoVI::rewrite(bool force, TDate&)
{
  return registra(TRUE,force);
}

int TClifoVI::remove(TDate&)
{
  TLocalisamfile& c=lfile(LF_CLIFO);

  c.remove();

  // Put here gest_vend() discrimination
  if (_gesven)
  {
    TLocalisamfile& v=lfile(LF_CFVEN);
    TLocalisamfile& rind=lfile(LF_INDSP);
    cancella(rind,1,_oldindirizzi);
    v.remove();
  }
  _oldindirizzi=0;

  return c.status();
}
