#include <config.h>
#include <execp.h>
#include <mask.h>
#include <mailbox.h>
#include <printapp.h>
#include <tabutil.h>
#include <utility.h>

#include <comuni.h>
#include <cfven.h>
#include <clifo.h>
#include <indsp.h> 
#include <mov.h>
#include <nditte.h>

#include "cg1.h"
#include "cg1200a.h"
#include "cg1200b.h"   
#include <pconti.h>

#define COMRF_ALIAS 50 
#define COMNASC_ALIAS 51 

enum pt { undefined = 0, elenco = 1, rubriche = 2, etichette = 3, vendite = 4 };
enum pw { clienti = 1, fornitori = 2, both = 3 };

bool mask2_reset_fields(TMask_field& mf, KEY k);

class TPrintclifo_app : public TPrintapp
{
  friend bool mask2_reset_fields(TMask_field& mf, KEY k);

  pt              _pr_type;
  pw              _pr_what;
  TRelation*      _rel;
  int             _cur_1, _cur_2;
  int             _sort;
  int             _interline;
  bool            _mov_only;
  TLocalisamfile* _mov;
  TLocalisamfile* _comuni;

  // etichette
  int _startrow, _rows_et, _cols_et, _startcol;

  // variable field slots
  TString _piva,_cpercip,_fax,_telex,_name,_telefono,_indir,_localita;               
  TString _cod_from,_cod_to,_data_stampa,_cofi,_d_c_ric,_d_alleg;
  TString _datanas,_comprov,_comnasc,_comune,_prov;
  long    _codice;   
  char    _tipocf,_tipoaper;
  bool    _gia_iniziati_fornitori;                       

public:

  virtual bool preprocess_page(int file, int counter);
  virtual bool preprocess_print(int file, int counter);
  virtual print_action postprocess_print(int file, int counter);
  virtual void preprocess_header();
  virtual bool user_create();
  virtual bool user_destroy();
  virtual bool set_print(int);
  
  int ccur() { return _sort == 1 ? _cur_1 : _cur_2; }

  const char* look_tab(const char* tabname, TString& cod, 
                       const char* fld = "S0");
  const char* get_field(int ln, const char* fn)
  { return current_cursor()->curr(ln).get(fn); }

  virtual void set_page (int file, int counter);
  void set_elenco();
  void set_rubriche();
  void set_etichette();
  void set_vendite(int f, int c) ;
  void process_link(int id, const char* txt);       
  void ultimo_codice(char tipo);          
  const char* compatta_ragsoc(TString& ragsoc,char tipoaper); 
  void header_elenco();
  void header_rubriche();
  TRectype& look_comuni(const char*);
  const char* descrizione_conto_ric(int,int,long);
  const char* descrizione_allegato(char,long);

  TPrintclifo_app() : TPrintapp(),_piva(18), _cpercip(10), _fax(50), _telex(50),
  _name(60), _telefono(90), _indir(70), _localita(90)
  { 
    _rel = NULL; _pr_type = undefined; _startrow = 2; _startcol = 3;
    _rows_et = 9; _cols_et = 40;
  }

};



/* -------------------------------------------------------------------- */
/* ---------------------------- Code ---------------------------------- */
/* -------------------------------------------------------------------- */


void TPrintclifo_app::process_link(int id, const char* txt)
{
  TString ss = "1|";
  ss << txt;
  TMessage fs("cg0 -1", MSG_LN, ss);
  TMailbox m;
  m.send(fs);             
  TExternal_app cg0("cg0 -1");
  if (cg0.run()) beep();
}

const char* TPrintclifo_app::look_tab(const char* tabname, TString& cod, 
                                      const char* fld)
{
  TTable tab(tabname);
  tab.curr().zero();
  tab.curr().put("CODTAB",cod);
  tab.read();
  if (tab.bad()) tab.curr().zero();
  return tab.curr().get(fld);
}

const char* TPrintclifo_app::descrizione_conto_ric(int gruppo, int conto, long sottoc)
{
  TLocalisamfile pconti(LF_PCON, FALSE);
  
  pconti.setkey(1);
  pconti.zero();
  pconti.put(PCN_GRUPPO, gruppo);
  pconti.put(PCN_CONTO,  conto);
  pconti.put(PCN_SOTTOCONTO, sottoc);  
  pconti.read();
  if (pconti.bad())
    pconti.zero();
  tmp = pconti.get(PCN_DESCR);
  
  return tmp;
}            

const char* TPrintclifo_app::descrizione_allegato(char tipocf,long cod)
{
  TLocalisamfile clifo(LF_CLIFO, FALSE);
  
  clifo.setkey(1);
  clifo.zero();
  clifo.put(CLI_TIPOCF, tipocf);
  clifo.put(CLI_CODCF , cod);
  clifo.read();
  if (clifo.bad())
    clifo.zero(); 
  _tipoaper = clifo.get_char(CLI_TIPOAPER);
  tmp       = clifo.get(CLI_RAGSOC);
  
  return tmp;
}            

TRectype& TPrintclifo_app::look_comuni(const char* cod)
{
  _comuni->zero();
  _comuni->put(COM_COM, cod);
  _comuni->read();
  if (_comuni->bad())
    _comuni->zero();

  return _comuni->curr();
}

bool TPrintclifo_app::preprocess_page(int file, int counter)
{
  TString s;
  int     g_ric,c_ric;
  long    s_ric,codall;
  
  switch (file)
  {
  case LF_CLIFO:
  {     
    if (_mov_only)
    {
      const TString16 tipocf(get_field(LF_CLIFO,CLI_TIPOCF));
      const TString16 codice(get_field(LF_CLIFO,CLI_CODCF));

      _mov->curr().zero();
      _mov->curr().put(MOV_TIPO, tipocf);
      _mov->curr().put(MOV_CODCF, codice);
      _mov->read();
      if (_mov->get(MOV_TIPO) != tipocf ||
          _mov->get(MOV_CODCF) != codice)
        return FALSE;
    }

    _tipocf = current_cursor()->curr(LF_CLIFO).get_char(CLI_TIPOCF);
    
    // set variable fields
    _cofi = get_field(LF_CLIFO, CLI_COFI);
    //_piva = get_field(LF_CLIFO, CLI_COFI);
    //if (_piva.empty()) _piva = get_field(LF_CLIFO, CLI_PAIV);
    _piva = get_field(LF_CLIFO, CLI_PAIV);
    _telefono = get_field(LF_CLIFO, CLI_PTEL); 
    if (!_telefono.empty()) _telefono << "/";
    _telefono << get_field(LF_CLIFO, CLI_TEL) << " ";
    s = get_field(LF_CLIFO, CLI_PTEL2);
    if (!s.empty()) s << "/";
    _telefono << s << get_field(LF_CLIFO, CLI_TEL2) << " ";
    s = get_field(LF_CLIFO, CLI_PTEL3);
    if (!s.empty()) s << "/";
    _telefono << s << get_field(LF_CLIFO, CLI_TEL3);
    _fax = get_field(LF_CLIFO, CLI_PFAX); 
    if (!_fax.empty()) _fax << "/";
    _fax << get_field(LF_CLIFO, CLI_FAX);
    _telex = get_field(LF_CLIFO, CLI_PTELEX); 
    if (!_telex.empty()) _telex << "/";
    _telex << get_field(LF_CLIFO, CLI_TELEX);
    _indir = get_field(LF_CLIFO, CLI_INDCF);
    g_ric  = atoi(get_field(LF_CLIFO, CLI_GRUPPORIC));     
    c_ric  = atoi(get_field(LF_CLIFO, CLI_CONTORIC));
    s_ric  = atol(get_field(LF_CLIFO, CLI_SOTTOCRIC));   
    codall = atol(get_field(LF_CLIFO, CLI_CODALLEG));  
    _datanas = get_field(LF_CLIFO, CLI_DATANASC);
    const TString16 tipoaper(get_field(LF_CLIFO, CLI_TIPOAPER));
    
    _d_alleg = "";        
    if (codall != 0)  
    {
      _d_alleg = descrizione_allegato(_tipocf,codall);
      if (_tipoaper == 'F')
      { 
        TString surname = _d_alleg.mid(30,50); surname.trim();
        _d_alleg        = _d_alleg.mid(0,30);  _d_alleg.trim();
        _d_alleg << " " << surname;
      }
    }

    _d_c_ric = descrizione_conto_ric(g_ric,c_ric,s_ric); 
    
    _d_c_ric = _d_c_ric.mid(0,31); 
    _d_alleg = _d_alleg.mid(0,26);
    
    if (!_indir.empty()) _indir << " ";
    _indir << get_field(LF_CLIFO, CLI_CIVCF);

    _localita = get_field(LF_CLIFO, CLI_LOCCF);
    if (!_localita.empty()) 
      _localita.trim(); 
    
    //modifica del 27/04/1995
    TString16 comcf = get_field(LF_CLIFO, CLI_COMCF);
    TRectype com = look_comuni(comcf);
    if (com.empty())
    {
      _comprov = _comune = _localita;
      _prov = "";
    }
    else
    {
      _comprov = com.get(COM_DENCOM);
      _comprov << " ";
      _comprov << com.get(COM_PROVCOM);
      _comune = (com.get(COM_DENCOM)).left(20);
      _prov   = com.get(COM_PROVCOM);
    }
    TString16 comnasc = get_field(LF_CLIFO, CLI_COMNASC);
    TRectype comn = look_comuni(comnasc);  
    _comnasc = (comn.get(COM_DENCOM)).left(29);
    _comnasc << " ";
    _comnasc << comn.get(COM_PROVCOM);
    //fine modifica
    
    _name = get_field(LF_CLIFO, CLI_RAGSOC);
    s = get_field(LF_CLIFO, CLI_CODANAGPER);
    _cpercip = "";
    
    if (s.not_empty()) _cpercip << tipoaper << " " << s;

    if (tipoaper == "F")
    { 
      TString surname = _name.mid(30,50); surname.trim();
      _name    = _name.mid(0,30);  _name.trim();
      _name << " " << surname;
    } 
    
    switch(_pr_type)
    {
    case elenco:
    case rubriche:
      if (_pr_what == both)
        if (_tipocf == 'F' && !_gia_iniziati_fornitori)
        {
          _gia_iniziati_fornitori = TRUE;
          printer().formfeed();
        }
      break;
    default:
      break;
    }
  }
  break;
 case LF_INDSP:
  current_cursor()->items();
  if (atoi(get_field(LF_INDSP,IND_CODIND)) == 0)
    return FALSE;
  _telefono = get_field(LF_INDSP, IND_PTEL); 
  if (!_telefono.empty()) _telefono << "/";
  _telefono << get_field(LF_INDSP, IND_TEL);
  _fax = get_field(LF_INDSP, IND_PFAX); 
  if (!_fax.empty()) _fax << "/";
  _fax << get_field(LF_INDSP, IND_FAX);
  _localita = get_field(LF_INDSP,IND_LOCALITA);
  if (!_localita.empty())
    _localita << " - ";
  _comuni->curr().zero();
  _comuni->curr().put(COM_STATO,get_field(LF_INDSP,IND_STATO));
  _comuni->curr().put(COM_COM,get_field(LF_INDSP,IND_COM));
  _comuni->read();
  _localita << _comuni->curr().get(COM_DENCOM);
  _localita << " ";
  _localita << _comuni->curr().get(COM_PROVCOM);
  break;
default:
  break;
}
  return TRUE;
}

print_action TPrintclifo_app::postprocess_print(int file, int counter)
{
  /*
     static bool more = FALSE;
     if (_pr_what == both)
     {
     if (more)
     { 
     more = FALSE;
     select_cursor(ccur());
     return NEXT_PAGE;
     }
     else
     {
     more = TRUE;
     select_cursor(ccur());
     return REPEAT_PAGE;
     }
     }                
     */
  return NEXT_PAGE;
}

bool gest_vend()
{
  TConfig c(CONFIG_DITTA,"cg");
  return (c.get("GesVen") == "X");
}

bool rdbtype_handler(TMask_field& f, KEY k)
{
  if (k == K_TAB) 
    //every time that change focus or value, check flag to enable button
  {     
    if (gest_vend())
      f.mask().enable(BUT_CG12_VENDITE);
    else
      f.mask().disable(BUT_CG12_VENDITE);
  }
  return TRUE;
}

bool mask_ctrl_handler(TMask_field& mf, KEY k)
{
  if (k == K_SPACE)
  {
    mf.mask().stop_run(mf.dlg());
  }
  return TRUE;
}

// set printrows

void TPrintclifo_app::set_page(int file, int counter)
{
  switch(_pr_type)
  {
  case elenco:
    if (file == LF_CLIFO)
      set_elenco();
    break;
  case rubriche:
    if (file == LF_CLIFO)
      set_rubriche();
    break;
  case etichette:
    if (file == LF_CLIFO)
      set_etichette();
    break;
  case vendite:
    set_vendite(file, counter);
  default:
    break;
  }
}

void TPrintclifo_app::ultimo_codice(char tipocf)
{
  TLocalisamfile clifo(LF_CLIFO,FALSE);
  
  char tipopr = tipocf;
  
  clifo.setkey(1);
  clifo.zero();   
  clifo.put(CLI_TIPOCF,tipocf); 
  
  for (clifo.read();!clifo.eof();clifo.next())
  {
    char tipo = clifo.get_char(CLI_TIPOCF);
    
    if (tipo != tipopr) break;
    
    _codice = clifo.get_long(CLI_CODCF);
  }
}                

const char* TPrintclifo_app::compatta_ragsoc(TString& ragsoc,char tipoa)
{    
  if (tipoa == 'F')
  {
    TString80 cognome, nome;
    cognome = ragsoc.mid(0,30);
    nome    = ragsoc.mid(30,20);
    cognome.trim(); nome.trim();
    
    ragsoc = cognome;
    ragsoc << " " << nome;
  }

  tmp = ragsoc;

  return tmp;
}

void TPrintclifo_app::preprocess_header()
{
  switch(_pr_type)
  {
  case elenco:
    header_elenco();
    break;
  case rubriche:
    header_rubriche();
    break;
  default:
    break;
  }
}

void TPrintclifo_app::header_elenco()
{
  reset_header();
  // intestazione
  const long firm = get_firm();  
  TString var;         
  int  j = 1;     
  char tipocf;
  TLocalisamfile ditte(LF_NDITTE);
  ditte.zero();
  ditte.put(NDT_CODDITTA, firm);
  ditte.read();
  if (ditte.bad()) ditte.zero();
  TString s(ditte.get(NDT_RAGSOC));
  
  set_header(j, "Ditta %ld %s@125gPag @#", firm, (const char*) s);
  set_header(j++, "@102gData %s", (const char*) _data_stampa);
  /*  
     if (_pr_what == both)
     {        
     current_cursor()->save_status();
     ++(*current_cursor());
     tipocf = current_cursor()->curr(LF_CLIFO).get_char(CLI_TIPOCF);   
     --(*current_cursor());
     current_cursor()->restore_status();
     }
     else
     */
  tipocf = current_cursor()->curr(LF_CLIFO).get_char(CLI_TIPOCF);
  
  if (tipocf == 'C')
    var = "Clienti";
  else
    if (tipocf == 'F')
      var = "Fornitori";
  
  set_header(j, "Elenco %s",(const char*) var);  
  
  if (_sort == 1)
    var = "Ordine di codice";
  else
    var = "Ordine alfabetico";
  
  set_header(j, "@30g%s", (const char*) var);
  
  if (_mov_only)
    set_header(j, "@55gSolo i movimentati");
  
  ultimo_codice(_tipocf);
  
  set_header(j++, "@102gUltimo cod.utilizzato  %ld" , _codice);
  
  if (_pr_what != both)
  {                 
    if (_cod_from.not_empty() || _cod_to.not_empty())
    {
      set_header(j, "Estremi selezione");
      if (_cod_from.not_empty()) 
        set_header(j, " da %s", (const char*) _cod_from);
      if (_cod_to.not_empty())  
        if (_sort == 1)
          set_header(j, " a %s", (const char*) _cod_to);
        else
          set_header(j, " a %s", (const char*) _cod_to);                                
      j++;
    }
  }                       
  
  set_header(j++, (const char *)(TString(132).fill('-')));
  set_header(j++, "  Codice Ragione sociale");
  set_header(j++, "@9gIndirizzo@56gC.A.P.@63gLocalita'");
  set_header(j++, "@9gTelefoni@90gFAX @115gTelex");
  set_header(j++, "@9gLuogo di nascita@45gData@56gPartita IVA   Codice fiscale");
  set_header(j++, "@9gConto di costo/ricavo@56gCodice allegato@90gPercipiente 770");
  set_header(j, (const char *)(TString(132).fill('-')));
}

void TPrintclifo_app::header_rubriche()
{
  reset_header();
  // intestazione
  const long firm = get_firm();
  TString var;         
  int  j = 1;
  char tipocf;     
  TLocalisamfile ditte(LF_NDITTE);
  ditte.zero();
  ditte.put(NDT_CODDITTA, firm);
  ditte.read();
  if (ditte.bad()) ditte.zero();
  TString s(ditte.get(NDT_RAGSOC));  
  set_header(j, "Ditta %ld %s@125gPag @#", firm, (const char*) s);
  set_header(j++, "@102gData %s", (const char*) _data_stampa);
  /*
     if (_pr_what == both)
     {
     current_cursor()->save_status();
     ++(*current_cursor());
     tipocf = current_cursor()->curr(LF_CLIFO).get_char(CLI_TIPOCF);
     --(*current_cursor());
     current_cursor()->restore_status();
     }
     else 
     */
  tipocf = current_cursor()->curr(LF_CLIFO).get_char(CLI_TIPOCF);
  
  if (tipocf == 'C')
    var = "Clienti";
  else
    if (tipocf == 'F')
      var = "Fornitori";   
  
  set_header(j, "Rubrica %s",(const char*) var);  
  
  if (_sort == 1)
    var = "Ordine di codice";
  else
    var = "Ordine alfabetico";
  
  set_header(j, "@30g%s", (const char*) var);
  
  if (_mov_only)
    set_header(j, "@55gSolo i movimentati");
  
  ultimo_codice(_tipocf);
  
  set_header(j++, "@102gUltimo cod.utilizzato  %ld" , _codice);
  
  if (_pr_what != both)
  {
    if (_cod_from.not_empty() || _cod_to.not_empty()) 
    {
      set_header(j, "Estremi selezione");
      if (_cod_from.not_empty())
        set_header(j, " da %s", (const char*) _cod_from);
      if (_cod_to.not_empty())
        if (_sort == 1)
          set_header(j, " a %s", (const char*) _cod_to);
        else
          set_header(j, " a %s", (const char*) _cod_to);
      j++;
    }
  }                       

  set_header(j++, (const char *)(TString(132).fill('-')));
  set_header(j++, "  Codice Ragione sociale@60gIndirizzo@100gC.A.P.@106gLocalita'@127gProv.");
  set_header(j++, "@9gPartita iva@25gTelefoni");
  set_header(j++, (const char *)(TString(132).fill('-')));
}

/*
   void TPrintclifo_app::set_elenco()
   {
   // body
   set_row(1,"$[r]@1s$[n] $[r]@pn$[n] #t", FLD(LF_CLIFO, CLI_TIPOCF),
   FLD(LF_CLIFO, CLI_CODCF,"@@@@@@"), &_name);
   set_row(2,"@9g#t@56g@s@63g#t @s @s", &_indir, FLD(LF_CLIFO, CLI_CAPCF),
   &_localita, FLD(-COMRF_ALIAS,COM_DENCOM), FLD(-COMRF_ALIAS,COM_PROVCOM));
   set_row(3,"@9g#t@90g#t@115g#t", &_telefono, &_fax, &_telex);
   set_row(4,"@9g@s @s@45g#t@56g#t@69g#t",FLD(-COMNASC_ALIAS, COM_DENCOM), 
   FLD(-COMNASC_ALIAS, COM_PROVCOM), &_datanas, &_piva,&_cofi);
   set_row(5,"@9g@3n @3n @6n #t@56g@n #t@90g#t",FLD(LF_CLIFO,CLI_GRUPPORIC),
   FLD(LF_CLIFO,CLI_CONTORIC), FLD(LF_CLIFO, CLI_SOTTOCRIC),&_d_c_ric,
   FLD(LF_CLIFO, CLI_CODALLEG), &_d_alleg, &_cpercip);
   
   for(int i = 0; i < _interline; i++)
   set_row(i+5,"");
   }
   */           
//modifica del 27/04/1995
void TPrintclifo_app::set_elenco()
{
  set_row(1,"$[r]@1s$[n] $[r]@pn$[n] #t", FLD(LF_CLIFO, CLI_TIPOCF),
          FLD(LF_CLIFO, CLI_CODCF,"@@@@@@"), &_name);
  set_row(2,"@9g#t@56g@s@63g#t", &_indir, FLD(LF_CLIFO, CLI_CAPCF),&_comprov);
  set_row(3,"@9g#t@90g#t@115g#t", &_telefono, &_fax, &_telex);
  set_row(4,"@9g#t@45g#t@56g#t@69g#t",&_comnasc, &_datanas, &_piva,&_cofi);
  set_row(5,"@9g@3n @3n @6n #t@56g@n #t@90g#t",FLD(LF_CLIFO,CLI_GRUPPORIC),
          FLD(LF_CLIFO,CLI_CONTORIC), FLD(LF_CLIFO, CLI_SOTTOCRIC),&_d_c_ric,
          FLD(LF_CLIFO, CLI_CODALLEG), &_d_alleg, &_cpercip);
  
  for(int i = 0; i < _interline; i++)
    set_row(i+5,"");
}

void TPrintclifo_app::set_rubriche()
{
  // body
  set_row(1,"$[r]@1s$[n] $[r]@pn$[n] #t", FLD(LF_CLIFO,CLI_TIPOCF),
          FLD(LF_CLIFO,CLI_CODCF,"@@@@@@"), &_name);
  //set_row(1,"@60g#t@100g@s@106g#t@127g@s", &_indir, FLD(LF_CLIFO, CLI_CAPCF),
  //        &_localita, FLD(-COMRF_ALIAS,COM_PROVCOM));
  set_row(1,"@60g#t@100g@s@106g#t@127g#t", &_indir, FLD(LF_CLIFO, CLI_CAPCF), &_comune, &_prov);
  set_row(2,"@9g#t@25g#t", &_piva,&_telefono);

  for(int i = 0; i < _interline; i++)
    set_row(i+4,"");
}

bool mask2_reset_fields(TMask_field& mf, KEY k)
{
  if (k == K_SPACE)
  {
    TPrintclifo_app& a =  (TPrintclifo_app&)main_app();
    TMask& m = mf.mask();
    m.set(FLD_CGB_STARTROW, a._startrow);
    m.set(FLD_CGB_STARTCOL, a._startcol);
    m.set(FLD_CGB_ROWSET,a._rows_et);
    m.set(FLD_CGB_COLSET, a._cols_et);
  }
  return TRUE;
}

void TPrintclifo_app::set_etichette()
{
  int r=_startrow;
  TString loccf=get_field(LF_CLIFO,CLI_LOCCF);

  reset_header();
  for (int i = 1; i < _startrow; i++)
    set_row(i,"");
  
  set_row(r++,   format("@%dg#-%dt",_startcol, _cols_et - _startcol), 
          &_name);
  set_row(r++, format("@%dg#-%dt",_startcol, _cols_et - _startcol), 
          &_indir);
  if (!loccf.empty())
    set_row(r++,format("@%dg#-%dt",_startcol, _cols_et - _startcol), &_localita);
  set_row(r++, format("@%dg@5s @%ds @2s",_startcol, 
                      _cols_et -  _startcol - 9),
          FLD(LF_CLIFO, CLI_CAPCF),
          FLD(-COMRF_ALIAS, COM_DENCOM),
          FLD(-COMRF_ALIAS, COM_PROVCOM));

  for (i = r; i <= _rows_et; i++)
    set_row(i,"");
}

void TPrintclifo_app::set_vendite(int f, int c)

{  TString* rigs = new TString(132);

   rigs->fill('-');

   reset_header();
   // intestazione
   const long firm = get_firm();
   TLocalisamfile ditte(LF_NDITTE);
   ditte.zero();
   ditte.put(NDT_CODDITTA, firm);
   ditte.read();
   if (ditte.bad()) ditte.zero();
   TString s(ditte.get(NDT_RAGSOC));

   switch (f)
   {
   case LF_CFVEN:
     /////////////////////////////////      
       //  Prints CFVEN information  //
       /////////////////////////////////
         set_header(1, "Ditta %ld %s @102gData @<@125gPag @#", firm, (const char*) s);
         set_header(2, "Dati Clienti/Fornitori per Vendite");
         set_header(3, (const char *)(TString(132).fill('-')));
         set_header(4,"  Codice Ragione sociale");
         set_header(5,"@9gNote Cli/For @25gLegale per contenz. @46gCat.Finanziaria @63gCat.Vendita @76gAss.Fiscale @93gZona @101gAgente @112gProvvigione");
         set_header(6,"@9gCod.Listino @25gCod. Magazzino @46gSpese da Addeb. @63gBolli Tr. @76gBolli R.B. @93gSpese incasso @112gBolli sup. 50.000");
         set_header(7,"@9gCli/For ass. @25gCod. Meccanografico @46gGest. Contratto @63gRid. Iva @76gUltimo sollecito @93gUltimo estr. conto @112gTitolo onorifico");
         set_header(8,"@9gSconto cliente @25gSconto di riga @46gSconto incond. @63gFatt. Sosp. @76gVs. Lettera Esenzione @112gNs. Lettera Esenz.");
         set_header(9,"@9gCod. ABI p.e. @25gCod. CAB p.e. @46gInd. Effetti @63gEmiss. Eff. @76gImporto Minimo @93gEffetti non acc. @112gScadenza effetti");
         set_header(10,"@9gInd.Documento @25gInd. Spedizione @46gNote Documento @63gCod.Mezzo @76gPorto @93gVettori");
         set_header(11,"@9gRaggr. ordini @25gImporto Minimo @46gImporto Massimo @63gPriorita ev. @76gTipo Evasione");
         set_header(12, (const char *)(TString(132).fill('-')));

         set_row(1,"$[r]@1s$[n] $[r]@pn$[n] #t", FLD(LF_CLIFO, CLI_TIPOCF),
                 FLD(LF_CLIFO, CLI_CODCF,"@@@@@@"), &_name);

         set_row(2,"@9g@2s @25g@2s @46g@2s @63g@2s @76g@2s @93g@2s @101g@3s @112g@n",
                 FLD(LF_CFVEN, CFV_CODNOTE),FLD(LF_CFVEN,CFV_CODLEG),
                 FLD(LF_CFVEN,CFV_CATFIN),FLD(LF_CFVEN,CFV_CATVEN),
                 FLD(LF_CFVEN,CFV_ASSFIS),FLD(LF_CFVEN,CFV_CODZONA),
                 FLD(LF_CFVEN,CFV_CODAG),FLD(LF_CFVEN,CFV_PROVV));

         set_row(3,"@9g@5s @25g@3s @46g@3s @3s @3s @3s @63g@f @76g@f @93g@f @112g@f",
                 FLD(LF_CFVEN,CFV_CODLIST),FLD(LF_CFVEN,CFV_CODMAG),
                 FLD(LF_CFVEN,CFV_CODSP1),FLD(LF_CFVEN,CFV_CODSP2),
                 FLD(LF_CFVEN,CFV_CODSP3),FLD(LF_CFVEN,CFV_CODSP4),
                 FLD(LF_CFVEN,CFV_ADDBOLLITR),FLD(LF_CFVEN,CFV_ADDBOLLIRB),
                 FLD(LF_CFVEN,CFV_ADDSPINC),FLD(LF_CFVEN,CFV_ADDBNS1500));

         set_row(4,"@9g@pn @25g@s @46g@f @63g@f @76g@d @93g@d @112g@2s",
                 FLD(LF_CFVEN,CFV_CODCFASS,"@@@@@@"),
                 FLD(LF_CFVEN,CFV_CODPRCF),FLD(LF_CFVEN,CFV_GESTCONTR),
                 FLD(LF_CFVEN,CFV_IVARID),FLD(LF_CFVEN,CFV_DATAESC),
                 FLD(LF_CFVEN,CFV_DATASOLL),FLD(LF_CFVEN,CFV_TITOLO));

         set_row(5,"@9g@n @25g@15s @46g@2s @63g@f @76g@s del @d @112g@s del @d",
                 FLD(LF_CFVEN,CFV_SCONTOCL),FLD(LF_CFVEN,CFV_SCONTOR),
                 FLD(LF_CFVEN,CFV_CODSCINC),FLD(LF_CFVEN,CFV_FATTSOSP),
                 FLD(LF_CFVEN,CFV_VSNRPROT),FLD(LF_CFVEN,CFV_VSDATAREG),
                 FLD(LF_CFVEN,CFV_NSNPROT),FLD(LF_CFVEN,CFV_NSDATAREG));

         set_row(6,"@9g@5pn @25g@5pn @46g@3,rn @63g@f @76g@pn @93g@s @112g@s",
                 FLD(LF_CFVEN,CFV_CODABIPR,"@@@@@"),
                 FLD(LF_CFVEN,CFV_CODCABPR,"@@@@@"),
                 FLD(LF_CFVEN,CFV_CODINDEFF),FLD(LF_CFVEN,CFV_EMEFFRICH),
                 FLD(LF_CFVEN,CFV_IMPMINEFF,"."),
                 FLD(LF_CFVEN,CFV_NONACCEFF),
                 FLD(LF_CFVEN,CFV_NONSCADEFF));

         set_row(7,"@9g@3,rn @25g@3,rn @46g@2s @53g@2s @63g@2s @76g@2s @93g@3pn @96g@3pn @103g@3pn",
                 FLD(LF_CFVEN,CFV_CODINDDOC),FLD(LF_CFVEN,CFV_CODINDSP),
                 FLD(LF_CFVEN,CFV_CODNOTESP1),FLD(LF_CFVEN,CFV_CODNOTESP2),
                 FLD(LF_CFVEN,CFV_CODSPMEZZO),FLD(LF_CFVEN,CFV_CODPORTO),
                 FLD(LF_CFVEN,CFV_CODVETT1,"@@@"),
                 FLD(LF_CFVEN,CFV_CODVETT2,"@@@"),
                 FLD(LF_CFVEN,CFV_CODVETT3,"@@@"));

         set_row(8,"@9g@s @25g@pn @46g@pn @63g@n @76g@2s",
                 FLD(LF_CFVEN,CFV_RAGGOR),FLD(LF_CFVEN,CFV_MINORD,"."),
                 FLD(LF_CFVEN,CFV_MAXORD,"."),FLD(LF_CFVEN,CFV_PREVORD),
                 FLD(LF_CFVEN,CFV_TIPOEVORD));
         if (current_cursor()->is_first_match(LF_INDSP))
         { // Test whether there are any Addresses. If so, prints
           // the header.
           set_row(9,"");
           set_row(10,"@9gIndirizzi di Spedizione");
           set_row(11,"@9g%t",rigs);
           set_row(12,"@9gCodice @17gRagione Sociale");
           set_row(13,"@17gIndirizzo @65gC.A.P. @72gLocalita");
           set_row(14,"@17gTelefono @60gFax @102gRiduzione IVA");
           set_row(15,"@9g%t",rigs);
         } else
           for (int i=0;i<_interline;i++)
             set_row(i+9,"");
         break;
         /////////////////////////////////////////
           //  End of printing CFVEN information  //
           /////////////////////////////////////////
           case LF_INDSP:
         //////////////////////////////////////////////////
         //  Prints INDSP information for each customer  //
         //////////////////////////////////////////////////

         set_row(1,"@9g@pn @17g@s",FLD(LF_INDSP,IND_CODIND,"@@@"),
                 FLD(LF_INDSP,IND_RAGSOC));
         set_row(2,"@17g@s @s   @65g@s  @72g#t",FLD(LF_INDSP,IND_INDIR),
                 FLD(LF_INDSP,IND_CIV),FLD(LF_INDSP,IND_CAP), &_localita);
         set_row(3,"@17g#t  @60g#t   @102g@f",&_telefono,&_fax,
                 FLD(LF_INDSP,IND_IVARID));
         current_cursor()->save_status();
         if (!current_cursor()->next_match(LF_INDSP))
           for (int i=0;i<_interline;i++)
             set_row(i+4,"");
         else
           set_row(4,"");
         current_cursor()->restore_status();
         /////////////////////////////////////////
           //  End of printing INDSP information  //
           /////////////////////////////////////////
             break;

       default:
         break;
       }
   delete rigs;
 }

bool TPrintclifo_app::set_print(int)
{
  disable_links();
  set_multiple_link(FALSE);

  TMask mask("cg1200a.msk");

  mask.set_handler(RDB_CG12_TYPE,      rdbtype_handler);
  mask.set_handler(BUT_CG12_ELENCO,    mask_ctrl_handler);
  mask.set_handler(BUT_CG12_RUBRICHE,  mask_ctrl_handler);
  mask.set_handler(BUT_CG12_ETICHETTE, mask_ctrl_handler);
  mask.run();
  
  force_setpage(FALSE);
  // set print type
  switch (mask.last_key())
  {
  case K_ESC: 
  case K_QUIT:
    return FALSE;
    break;
  case BUT_CG12_ELENCO:
    _pr_type = elenco;
    break;
  case BUT_CG12_ETICHETTE:
  {
    TMask mask2("cg1200b.msk");
    
    /* TBI read/save from - to config file */
    _pr_type = etichette;

    mask2.set_handler(BUT_CGB_RESET,  mask2_reset_fields);
    
    mask2.field(FLD_CGB_ROWSET).set(format("%d",_rows_et));
    mask2.field(FLD_CGB_COLSET).set(format("%d",_cols_et));
    
    mask2.field(FLD_CGB_STARTROW).set(format("%d",_startrow));
    mask2.field(FLD_CGB_STARTCOL).set(format("%d",_startcol));

    // set defaults

    if (mask2.run() == K_ESC)
      return FALSE;

    _startrow  = atoi(mask2.get(FLD_CGB_STARTROW));
    _startcol  = atoi(mask2.get(FLD_CGB_STARTCOL));
    _rows_et  = atoi(mask2.get(FLD_CGB_ROWSET));
    _cols_et  = atoi(mask2.get(FLD_CGB_COLSET));
    force_setpage();
    break;
  }
  case BUT_CG12_RUBRICHE:
    _pr_type = rubriche;
    break;
  case BUT_CG12_VENDITE:
    _pr_type = vendite;
    force_setpage();
    break;
  }
  
  if (_pr_type != etichette)
  {
    set_multiple_link(TRUE);
    enable_link("Collegamento clienti e fornitori : ", 'r');
  }

  _sort        = mask.get_int(RDB_CG12_SORT);
  _pr_what     = (pw) mask.get_int(RDB_CG12_TYPE);
  _interline   = mask.get_int(LST_CG12_INTERLINE);
  _mov_only    = mask.get_bool(CHK_CG12_MOVIM);   
  char tipoafr = mask.get(F_TIPOAPERFR)[0];
  char tipoato = mask.get(F_TIPOAPERTO)[0];
  TDate data_stampa (mask.get(F_DATA_STAMPA));
  _data_stampa = data_stampa.string();
  _codice = 0;

  select_cursor(ccur()); 
  
  TRectype tr1(current_cursor()->curr());
  tr1.zero();
  TRectype tr2(tr1);

  if (_pr_what != both)
  {
    // filter
    tr1.put(CLI_TIPOCF, _pr_what == clienti ? "C" : "F");
    tr2.put(CLI_TIPOCF, _pr_what == clienti ? "C" : "F");
    short fromid, toid;
    TString16 nome_campo;

    if (_sort == 1)
    {
      fromid = (_pr_what == clienti) ? FLD_CLI_CODFR : FLD_FOR_CODFR;
      toid = (_pr_what == clienti) ? FLD_CLI_CODTO : FLD_FOR_CODTO;
      nome_campo = CLI_CODCF;
    }
    else 
    {
      fromid = (_pr_what == clienti) ? FLD_CLI_RAGSOCFR : FLD_FOR_RAGSOCFR;
      toid = (_pr_what == clienti) ? FLD_CLI_RAGSOCTO : FLD_FOR_RAGSOCTO;
      nome_campo = CLI_RAGSOC;
    }
    TString cod_from(mask.get(fromid));
    TString cod_to(mask.get(toid));  
    
    if (cod_from.not_empty()) tr1.put(nome_campo, cod_from);
    if (cod_to.not_empty()) tr2.put(nome_campo, cod_to);
    
    if (_sort == 1)
    {
      _cod_from = cod_from;
      _cod_to   = cod_to;                   
    }
    else
    {
      _cod_from = compatta_ragsoc(cod_from,tipoafr);
      _cod_to   = compatta_ragsoc(cod_to,tipoato);
    }
  }
  current_cursor()->setregion(tr1, tr2);
  
  return TRUE;
}


bool TPrintclifo_app::preprocess_print(int file, int counter)
{
  reset_print();
  if (_pr_type == undefined)
    return set_print(counter);
  
  if (file == LF_CLIFO)
    if (_pr_what == both)
      _gia_iniziati_fornitori = FALSE;
  
  return TRUE;
}

bool TPrintclifo_app::user_create()
{
  // set relation and cursors
  _rel    = new TRelation(LF_CLIFO);   
  _rel->add(LF_COMUNI, "STATO==STATOCF|COM==COMCF", 1, 0, COMRF_ALIAS);
  _rel->add(LF_COMUNI, "STATO==STATONASC|COM==COMNASC", 1, 0, COMNASC_ALIAS);
  if (gest_vend())
  {
    _rel->add(LF_CFVEN,"TIPOCF=TIPOCF|CODCF=CODCF");
    _rel->add(LF_INDSP,"TIPOCF=TIPOCF|CODCF=CODCF");
  }

  _mov  = new TLocalisamfile(LF_MOV); _mov->setkey(3);   
  _comuni = new TLocalisamfile(LF_COMUNI);
  _cur_1 = add_cursor(new TCursor(_rel,"",1));
  _cur_2 = add_cursor(new TCursor(_rel,"",2));
  add_file(LF_CLIFO);
  if (gest_vend())
  {
    add_file(LF_CFVEN,LF_CLIFO);
    add_file(LF_INDSP,LF_CLIFO);
  }
  enable_print_menu();
  return TRUE;
}

bool TPrintclifo_app::user_destroy()
{
  if (_rel) 
    delete _rel;
  delete _mov;
  delete _comuni;
  return TRUE;
}

int cg1200(int argc, char* argv[])
{
  TPrintclifo_app app;
  app.run(argc, argv, "Stampa Clienti/Fornitori");    
  return 0;
}
