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

#include "soggetti.h"
#include "sezioni.h"

#include "at2.h"
#include "at2300a.h"
#include "atlib.h"

#define ALIAS_LCP	100
#define ALIAS_TCS	200

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

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

class TStampaEsclusi : public TPrintapp
{
  static bool filter_func_esclusi(const TRelation* rel);

  TRelation*        	_rel;
  TMask*            	_msk;
  TEti_esclusi_form*	_form_eti;
  TAssoc_array				_categorie;
  TString16						_tipoesc;
  TDate								_termineesc;
  TParagraph_string 	_cognome_nome;
  TDate 							_data_stampa;
	ts 	      					_tipostampa;
	TString16						_codsez, _codsot;
	int									_etlarghezza, _etcolonne, _totale, _contatore;
  
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 header_sezione(const TString16 codsez, const TString16 codsot);
  void footer_sezione();
  void fine_stampa();
  TMask& app_mask() { return *_msk; }
  TStampaEsclusi() : _data_stampa(TODAY), _cognome_nome("",25) {}
};

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

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

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

void TStampaEsclusi::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 TStampaEsclusi::set_page(int file, int cnt)
{ 
	// costruzione etichette
	switch (_tipostampa)
	{
		case etichette:
		{
			TPrint_section& corpo = _form_eti->get_body();
			corpo.update();
  		for (word i = 0; i < corpo.height(); i++)
  		{
  			TPrintrow& riga = corpo.row(i);
  			set_row(i+1,riga);
			}  			
			// serve perch� alla prossima etichetta rifaccia la setpage
			// altrimenti stampa sempre la stessa etichetta			
			force_setpage(true);
		}
		break;
		case elenco:
		{
			set_row(1,"@0g@pn", FLD(LF_SOGGETTI,SOG_CODICE,"########"));
			set_row(1,"@9g@6,rs", FLD(LF_SOGGETTI,SOG_TESSAVIS));
			set_row(1,"@16g@S", FLD(LF_SOGGETTI,SOG_CATDON));
			set_row(1,"@19g#a", &_cognome_nome);
			set_row(1,"@45g@ld", FLD(LF_SOGGETTI,SOG_DATANASC));
			set_row(1,"@56g@S", FLD(LF_SOGGETTI,SOG_ESCLUSO));
			set_row(1,"@59g@ld", FLD(LF_SOGGETTI,SOG_TERMESCL));
			set_row(1,"@70g@S", FLD(LF_SOGGETTI,SOG_MOTESCL));
		}
		break;
	}					
}

bool TStampaEsclusi::filter_func_esclusi(const TRelation * rel)
{   
	bool filtrato = true;
	TLocalisamfile& sog = rel->lfile();
	//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);
	}	
	// filtro per termine esclusione
	if (filtrato && app()._termineesc.ok())
	{
		const TDate terminesog = sog.get_date(SOG_TERMESCL);
		filtrato = terminesog <= app()._termineesc;
	}			
  return filtrato;
}

bool TStampaEsclusi::preprocess_page(int file, int counter)
{
	if (_tipostampa == elenco)
	{
		TRectype& recsog = current_cursor()->curr();
		TString80 nome = recsog.get(SOG_COGNOME);
		nome << " ";
		nome << recsog.get(SOG_NOME);
		_cognome_nome = nome;
		// salto pagina se cambio sezione
		const TString16 codsez = recsog.get(SOG_CODSEZ);		
		const TString16 codsot = recsog.get(SOG_CODSOT);		
		if ((_codsez!=codsez)||(_codsot!=codsot))
		{
			if (_codsez != "**")
				footer_sezione();
			_contatore = 0;				
			_codsez = codsez;
			_codsot = codsot;
			header_sezione(codsez, codsot);
		}
	}		
	if (_tipostampa==etichette)		
		if (printer().rows_left() < _form_eti->get_body().height())
			printer().formfeed();
	_contatore++;			
	_totale++;
  return true;
}

print_action TStampaEsclusi::postprocess_print(int file, int counter)
{ 
	if (_contatore > 0)
		footer_sezione();
	fine_stampa();	
	return NEXT_PAGE;
}

void TStampaEsclusi::header_sezione(const TString16 codsez, const TString16 codsot)
{
	const TString80 densez = current_cursor()->curr(LF_SEZIONI).get(SEZ_DENSEZ);
	const TString80 densot = current_cursor()->curr(LF_SEZIONI).get(SEZ_DENSOT);
	TString intestazione(100);
	intestazione = "Sezione: ";
	intestazione << codsez;
	intestazione << "/";
	intestazione << codsot;
	intestazione << " ";
	intestazione << densez;
	if (densot.not_empty())
	{
		intestazione << "/";
		intestazione << densot;
	}		
	intestazione.center_just();
	set_header(1,"@0g%s", (const char*) intestazione);
	return;
}

void TStampaEsclusi::footer_sezione()
{
	// stampa totale soggetti appartenenti alla sezione
  if (_tipostampa==elenco)
	{
		reset_footer();
		TString sep(80);
		sep.fill('-');
		set_footer(2, (const char *) sep);
		set_footer(3,"TOTALE SOGGETTI STAMPATI %d", _contatore);
		printer().formfeed(); 
		reset_footer();
	}	
}
                          
void TStampaEsclusi::fine_stampa()
{
	// stampa totale soggetti a fine stampa
  if (_tipostampa==elenco)
	{
		reset_footer();
		TString sep(80);
		sep.fill('-');
		set_footer(2, (const char *) sep);
		if (_totale > 0 && _totale != _contatore)
		{
			set_footer(3,"TOTALE SOGGETTI STAMPATI %d", _totale);
			printer().formfeed();		
		}			
		reset_footer(); 
	}	
}

bool TStampaEsclusi::set_print(int)
{
  TPrinter& p = printer();
	p.read_configuration();
	_tipostampa = undefined;
  KEY tasto;
  tasto = _msk->run();
  switch (tasto)
  {
  case F_ELENCO:
  {
  	_tipostampa = elenco;
  	_codsez = "**";
  	_codsot = "**";
  	_contatore = 0;
  	_totale = 0;
  }	
  break;
  case F_ETICHETTE:
  	_tipostampa = (configura_stampante(p, "AT_ETICHETTE", "etichette")) ? etichette : undefined;
 	break;
  }	
	if (_tipostampa != undefined)
  {
    reset_files(); 
    add_file(LF_SOGGETTI);
		filtra_sezioni();
		// filtro per tipo esclusione
    _tipoesc = _msk->get(F_TIPO);
    if (_tipoesc.not_empty())
    	current_cursor()->setfilter(format("ESCLUSO == \"%s\"",(const char*)_tipoesc));
 		else      
     	current_cursor()->setfilter("ESCLUSO != \"\"");
    // filtro per categorie
    _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);
		// filtro per termine esclusione	  	
    _termineesc = _msk->get(F_DATA);
		current_cursor()->set_filterfunction(filter_func_esclusi);
		reset_print();		
		printer().footerlen(0);		
    crea_intestazione();
    return true;
  }
  else
    return false;
}

void TStampaEsclusi::crea_intestazione()
{
  reset_header();
  if (_tipostampa == elenco)
  {
  	TString sep(100);
  	sep = "ELENCO ESCLUSI";
  	if (_tipoesc.not_empty())
  	{
  		sep << " ";
  		sep << _tipoesc;
		}
		if (_termineesc.ok())
		{
	  	sep << " termine fino al ";
  		sep << _termineesc.string();
		}
		sep.center_just();
  	set_header(2, "@0g%s", (const char*) sep);
  	const TString16 data_stampa = _data_stampa.string();
  	set_header(2,"@0g%10s", (const char*) data_stampa);
  	sep = "";
  	sep << "Pag. @#";
  	set_header(2, "@78g%s", (const char*) sep);  
  	sep = "";
  	sep.fill('-');
  	set_header(3, (const char *) sep);
  	set_header(4,"@0gCodice@9gC.@12gCognome e nome@38gNato il@49gEsclusione@63gMotivo");
  	set_header(5,"@49gTipo Termine");  
  	set_header(6,"@0g--------@9g--@12g-------------------------@38g----------@49g-------------@63g------------------------------");
  	printer().footerlen(3);
	}  	
}

bool TStampaEsclusi::user_create()
{
  _rel = new TRelation(LF_SOGGETTI);
  _rel->add("TCS", "CODTAB==STATO",1,0,ALIAS_TCS);
  _rel->add("LCP", "CODTAB==DOM_CODLOC",1,0,ALIAS_LCP);
  _rel->add(LF_COMUNI, "COM==DOM_CODCOM");
  _rel->add(LF_SEZIONI, "CODSEZ==CODSEZ|CODSOT==CODSOT");
  add_cursor(new TCursor(_rel, "", 3));
  _msk = new TMask("at2300a");
  TConfig config(CONFIG_STUDIO);
  TString16 etformato = config.get("EtFormato");
  _etlarghezza = config.get_int("EtLarghezza");
  _etcolonne = config.get_int("EtColonne");
	_form_eti = new TEti_esclusi_form(etformato);
  return true;
}

bool TStampaEsclusi::user_destroy()
{
  delete _form_eti;
  delete _msk;
  delete _rel;
  return true;
}

int at2300(int argc, char* argv[])
{
  TStampaEsclusi a;
  a.run(argc, argv, "Soggetti esclusi");
  return 0;
}