#include <form.h>
#include <mask.h>
#include <printapp.h>

#include "soggetti.h"
#include "sezioni.h"
#include "atopera.h"
#include "atropera.h"

#include "at7.h"
#include "at7100a.h"

#include "at7100.h"
#define ALIAS_COMDOM 501
#define ALIAS_COMNAS 500 
#define ALIAS_LCP    100

enum ts { undefined = 0, elenco = 1, tessere = 2 };

// definizione form per tessere associative
class TTessere_form : public TForm
{
public:
	
	virtual TCursor* cursor() const;
	virtual TRelation* relation() const;
	TPrint_section& get_body() { return section('B'); } ;
  TTessere_form(): TForm() {};
  TTessere_form(const char* form, const char * code = "", int editlevel = 0, const char* desc = "")
    						: TForm(form,code,editlevel,desc) {};
  virtual ~TTessere_form() {};
};

class TStampaTessere : public TPrintapp
{
  TRelation*			_rel;
  TMask*      		_msk;
  TAssoc_array		_categorie;
  TTessere_form*	_form_pag;
  int							_numdon;
  bool						_aggiorna;
  int 						_cur;
  TDate 					_data_stampa, _datault;
	TString					_riepilogodon;
	ts 	      			_tipostampa;
	TString16				_codsez, _codsot;
  int							_contatore, _totfinestampa, _progope;
  bool						_sttess2;
  int							_numdon2;
	TString16				_catini2, _catfin2;

  static bool filter_func_auto(const TRelation* rel);
  
protected:
  virtual bool user_create();
  virtual bool user_destroy();
  virtual bool set_print(int m);
  virtual void set_page(int file, int cnt);
  virtual bool preprocess_page(int file, int counter);
  virtual print_action postprocess_print(int file, int counter);

public:
  void crea_intestazione();
  void filtra_sezioni();
  void footer_sezione();
  void fine_stampa();
  void header_sezione(const TString16 codsez, const TString16 codsot);
  TMask& app_mask() { return *_msk; }
  TStampaTessere() : _data_stampa(TODAY), _riepilogodon(35) {}
};

HIDDEN inline TStampaTessere& app() { return (TStampaTessere&) main_app(); }

TCursor* TTessere_form::cursor() const { return app().current_cursor(); }

TRelation* TTessere_form::relation() const { return cursor()->relation(); }

void TStampaTessere::header_sezione(const TString16 codsez, const TString16 codsot)
{   
	TPrintrow row;
	TString256 intestazione;
	const TString80 densez = current_cursor()->curr(LF_SEZIONI).get(SEZ_DENSEZ);
	const TString80 densot = current_cursor()->curr(LF_SEZIONI).get(SEZ_DENSOT);
	intestazione = "Sezione: ";
	intestazione << codsez;
	if (codsot.not_empty())
	{
		intestazione << "/";
		intestazione << codsot;
	}		
	intestazione << " ";
	intestazione << densez;
	if (densot.not_empty())
	{
		intestazione << "/";
		intestazione << densot;
	}		
	//intestazione.center_just();
	//set_header(1,"@0g%s", (const char*) intestazione);
	row.put((const char*) intestazione);
	printer().print(row);			
	row.reset();
	printer().print(row);			
  row.put("@8gCognome@34gNome@60gData nasc.@71gTessera@78gUld.donaz.@89gTot.",1);
	printer().print(row);			
  row.put("@8g-------------------------@34g-------------------------@60g----------@71g-------@78g----------@89g----",1);
	printer().print(row);			
	return;
}

void TStampaTessere::footer_sezione()
{
	// stampa totale soggetti a fine pagina
	TPrintrow row;
	TString rigastampa = "";
	row.reset();
	printer().print(row);			
	rigastampa.format("TOTALE SOGGETTI PER SEZIONE %d", _contatore);
	row.put((const char*) rigastampa);
	printer().print(row);			
	row.reset();
	printer().print(row);			
}

void TStampaTessere::fine_stampa()
{
	// stampa totale soggetti a fine stampa
	TPrintrow row;
	TString rigastampa = "";
	rigastampa.fill('-',80);
	row.put((const char*) rigastampa);
	printer().print(row);			
	row.reset();
	printer().print(row);			
	rigastampa.format("TOTALE SOGGETTI DA TESSERARE %d", _totfinestampa);
	row.put((const char*) rigastampa);
	printer().print(row);			
	printer().formfeed();
}
         
print_action TStampaTessere::postprocess_print(int file, int counter)
{ 
	if (_tipostampa == elenco)
	{
		if (_contatore > 0)
			footer_sezione();
		if (_totfinestampa > 0 && _contatore != _totfinestampa)
			fine_stampa();				
	}			
	return NEXT_PAGE;
}
         
void TStampaTessere::filtra_sezioni()
{
 	const TString16 sezini = _msk->get(F_SEZINI);
 	const TString16 sotini = _msk->get(F_SOTINI);
 	const TString16 sezfin = _msk->get(F_SEZFIN);
 	const TString16 sotfin = _msk->get(F_SOTFIN);
  TRectype da(LF_SOGGETTI);
  TRectype a(LF_SOGGETTI);   
	if (sezini.not_empty())  
		da.put(SOG_CODSEZ, sezini);
  if (sotini.not_empty())
		da.put(SOG_CODSOT, sotini);
  if (sezfin.not_empty())
		a.put(SOG_CODSEZ, sezfin);
  if (sotfin.not_empty())
		a.put(SOG_CODSOT, sotfin);
	current_cursor()->setregion(da, a);
}	

void TStampaTessere::set_page(int file, int cnt)
{
	switch (_tipostampa)
	{
		case tessere:
    {
			TPrint_section& corpo = _form_pag->get_body();
			corpo.reset();
		  TForm_item& rigadon = corpo.find_field(TES_RIGADON1);
			rigadon.set(_riepilogodon);
			corpo.update();
			for (word i = 0; i < corpo.height(); i++)
			{
				TPrintrow& riga = corpo.row(i);
				set_row(i+1,riga);
			}  			
			force_setpage(TRUE);	// serve perch� alla prossima etichetta rifaccia la setpage
														// altrimenti stampa sempre la stessa etichetta
		}
		break;
		case elenco:
		{
			set_row(1,"@8g@S", FLD(LF_SOGGETTI,SOG_COGNOME));
			set_row(1,"@34g@S", FLD(LF_SOGGETTI,SOG_NOME));
			set_row(1,"@60g@ld", FLD(LF_SOGGETTI,SOG_DATANASC));
			set_row(1,"@71g@S", FLD(LF_SOGGETTI,SOG_TESSAVIS));
			set_row(1,"@78g@ld", FLD(LF_SOGGETTI,SOG_DATAULTDON));
			set_row(1,"@89g@pn", FLD(LF_SOGGETTI,SOG_TOTDON, "###"));
		}
		break;
	}																
}

bool TStampaTessere::filter_func_auto(const TRelation* rel)
{   
	bool filtrato = TRUE;
	TLocalisamfile& sog = rel->lfile(); 
	filtrato = !(sog.get_bool(SOG_T_STAMPATA));
	if (filtrato)
		filtrato = (sog.get_int(SOG_TOTDON) >= app()._numdon);
	if (filtrato)
		filtrato = (sog.get_date(SOG_DATAULTDON) > app()._datault);		
	if (filtrato)		
	{ 
		// filtro per categorie
		TAssoc_array& categorie = app()._categorie;
		if (categorie.items() != 0)
		{
			const TString16 cat = sog.get(SOG_CATDON);
			filtrato = categorie.is_key((const char*) cat);
		}	
	}		
  return filtrato;
}

bool TStampaTessere::preprocess_page(int file, int counter)
{                              
	TLocalisamfile& sogg = current_cursor()->file(LF_SOGGETTI);
	if (_tipostampa == elenco)
	{
		const TString16 codsez = sogg.get(SOG_CODSEZ);		
		const TString16 codsot = sogg.get(SOG_CODSOT);		
		// salto pagina se cambio sezione
		if ((_codsez!=codsez)||(_codsot!=codsot))
		{
			if (_codsez != "**")
				footer_sezione();
			_codsez = codsez;
			_codsot = codsot;
			header_sezione(codsez, codsot);
			_contatore = 0;
		}			
		_contatore++;
		_totfinestampa++;
	}
	const int totdon = sogg.get_int(SOG_TOTDON);
	if (_tipostampa == tessere)
	{
		const TDate dataultima = sogg.get(SOG_DATAULTDON);
		_riepilogodon = "";
		if (totdon != 0)	
		{	
			_riepilogodon = "Donazioni fino al ";
			_riepilogodon << dataultima.string();
			_riepilogodon << " n.";
			_riepilogodon << totdon;
		}	
	}		
	if (_aggiorna)
	{
		sogg.put(SOG_T_STAMPATA,TRUE);
		TString16 catdon = sogg.get(SOG_CATDON);
		if ((totdon >= _numdon2) && (catdon == _catini2) && _sttess2)
			sogg.put(SOG_CATDON, _catfin2);
		sogg.rewrite();
		TLocalisamfile atropera(LF_ATROPERA);
		atropera.zero();
		atropera.put(ROP_PROGOPE, _progope);
		atropera.put(ROP_CODICE, sogg.get(SOG_CODICE));
		atropera.write();
	}		
  return TRUE;
}

bool TStampaTessere::set_print(int m)
{ 
  TPrinter& p = printer();
	p.read_configuration();
	_tipostampa = undefined;
  KEY tasto;
  tasto = _msk->run();
  switch (tasto)
  {
  case F_ELENCO:
  	_tipostampa = elenco;
  break;
  case F_TESSERE:
  {
  	_tipostampa = tessere;
    p.read_configuration("AT_TESSERE");
    p.set_printtype(winprinter);
    if (p.set())
			message_box("Stampante configurata per stampa tessere");    	
		else
		{
			_tipostampa = undefined;			
			message_box("Operazione di stampa tessere annullata");    	
		}	
	}  	
  break;
  }	
	if (_tipostampa != undefined)
  {   
  	_codsez = "**";
  	_codsot = "**";
    reset_files(); 
    add_file(LF_SOGGETTI);
    filtra_sezioni();
    _numdon = _msk->get_int(F_NUMDON);
    _aggiorna = _msk->get_bool(F_AGGIORNA);
    _datault = _msk->get_date(F_DATAULT);
    _categorie.destroy();   	
  	const TString16 catpri = _msk->get(F_CAT1);
  	const TString16 catsec = _msk->get(F_CAT2);
  	const TString16 catter = _msk->get(F_CAT3);
  	const TString16 catqua = _msk->get(F_CAT4);
  	const TString16 catqui = _msk->get(F_CAT5);
  	const TString16 catses = _msk->get(F_CAT6);
  	if (catpri.not_empty())
  		_categorie.add((const char*) catpri);
  	if (catsec.not_empty())
  		_categorie.add((const char*) catsec);
  	if (catter.not_empty())
  		_categorie.add((const char*) catter);
  	if (catqua.not_empty())
  		_categorie.add((const char*) catqua);
  	if (catqui.not_empty())
  		_categorie.add((const char*) catqui);
  	if (catses.not_empty())
  		_categorie.add((const char*) catses);
 		current_cursor()->set_filterfunction (filter_func_auto, TRUE);
 		_contatore = 0;
 		_totfinestampa = 0;
 		if (_aggiorna)
 		{
			TLocalisamfile atopera(LF_ATOPERA);
			atopera.last();
			_progope = atopera.get_int(OPE_PROGOPE);
			_progope++;
			atopera.zero();
			atopera.put(OPE_PROGOPE, _progope);
			atopera.put(OPE_CODSEZ,_msk->get(F_SEZINI));
			atopera.put(OPE_CODSOT,_msk->get(F_SOTINI));
			atopera.put(OPE_CODSEZ2,_msk->get(F_SEZFIN));
			atopera.put(OPE_CODSOT2,_msk->get(F_SOTFIN));
			atopera.put(OPE_DATA1,_data_stampa);
			atopera.put(OPE_DATA2,_datault);
			atopera.put(OPE_NUMERO1,_numdon);
			atopera.put(OPE_UTENTE,user());
			atopera.put(OPE_TIPOOPE,'T');
			atopera.write();
		}
		reset_print();
		printer().footerlen(0);		
		crea_intestazione();
    return TRUE;
  }
  else
    return FALSE;
}

bool TStampaTessere::user_create()
{
  _rel = new TRelation(LF_SOGGETTI);
  _rel->add(LF_COMUNI, "COM==DOM_CODCOM",1,0,ALIAS_COMDOM);
  _rel->add(LF_COMUNI, "COM==COMNASC",1,0,ALIAS_COMNAS);
  _rel->add("LCP", "CODTAB==DOM_CODLOC",1,0,ALIAS_LCP);
  _rel->add(LF_SEZIONI, "CODSEZ==CODSEZ|CODSOT==CODSOT");
	//cursore ordinamento per sezione+sottogruppo+cognome+nome  
  _cur = add_cursor(new TCursor(_rel, "", 3));
  _msk = new TMask("at7100a");
  TConfig config(CONFIG_STUDIO);
  _numdon2 = config.get_int("NumDon2");
  _catini2 = config.get("CatIni2");
  _catfin2 = config.get("CatFin2");
  _sttess2 = config.get_bool("StTess2");
  _form_pag = new TTessere_form("ATTESSER");
  return TRUE;
}

void TStampaTessere::crea_intestazione()
{
  reset_header();
  if (_tipostampa == elenco)
  {
  	TString sep(80);
  	sep = "ELENCO SOGGETTI DA TESSERARE";
		sep.center_just(80);
  	set_header(1, "@0g%s", (const char*) sep);
  	TString16 data_stampa = _data_stampa.string();
  	set_header(1,"@0g%10s", (const char*) data_stampa);
  	sep = "";
  	sep << "Pag. @#";
 		set_header(1, "@72g%s", (const char*) sep);  
  	sep = "";
  	sep.fill('-');
  	set_header(2, (const char *) sep);
  	set_header(3, "");
  	/*
	  set_header(4,"@0gCognome@26gNome@52gData nasc.@63gTessera");
	  set_header(5,"@0g-------------------------@26g-------------------------@52g----------@63g-------");
  	printer().footerlen(3);
		*/  	
	}  	
}

bool TStampaTessere::user_destroy()
{
  delete _form_pag;
  delete _msk;
  delete _rel;
  return TRUE;
}

int at7100(int argc, char* argv[])
{
  TStampaTessere a;
  a.run(argc, argv, "Stampa tessere associative complessive");
  return 0;
}