#include <applicat.h>
#include <automask.h>
#include <execp.h>
#include <progind.h>
#include <reprint.h>
#include <reputils.h>
#include <utility.h>

#include "pg0001.h"
#include "pg0001100a.h"

#include "textset.h"


#include "clifo.h"
#include "comuni.h"
#include "doc.h"
#include "rdoc.h"

#include "..\cg\cglib01.h"
#include "..\ve\velib.h"


///////////////////////////////////////////////////////////
// TPaghe_textset
///////////////////////////////////////////////////////////

class TPaghe_recset : public TAS400_recordset
{
	TAssoc_array _index;

protected:
  void add_field(const char* name = "Filler", char tipo = 'a', int len = 0, int from = -1, 
								 const char* def = NULL);

public:
  TPaghe_recset(const char * query);
};

void TPaghe_recset::add_field(const char* name, char tipo, int len, int from, 
								 const char* def)
{
	const bool required = false;
  const TFieldtypes t = tipo == 'n' ? _longzerofld : _alfafld;
  const int pos = from - 1;
  if (def && *def)
  {
    CHECKS(def == NULL || (int)strlen(def) <= len, "Invalid default value ", def);
    TVariant var(def); var.convert_to(t);
    create_field(name, pos, len, t, required, var);
  }
  else
    create_field(name, pos, len, t, required);
}


TPaghe_recset::TPaghe_recset(const char * query)
             : TAS400_recordset(TString("AS400(124)\n") << query)
{
  const char a = 'a';
  const char n = 'n';
  const bool o = true;
  const bool f = false;
  
  add_field("CLA01", n, 4, 1);	
  add_field("CLM01", n, 2, 5);
  add_field("CLAZI", n, 9, 7);
  add_field("CLF01", a, 4, 16);
  add_field("CLCZN", a, 1, 20);
  add_field("CLCTR", a, 4, 21);
  add_field("CLNCD", n, 3, 25);
  add_field("CLILR", n, 11,28);
  add_field("CLTEL", a, 1, 39);
  add_field("CLANN", a, 1, 40);
  add_field("CLDTC", n, 6, 41);
  add_field("CLA02", n, 4, 47);
  add_field("CLM02", n, 2, 51);
  add_field("CLAZ1", n, 9, 53);
  add_field("CLPRG", n, 6, 62);
  add_field("CLDTV", n, 6, 68);
  add_field("CLF02", a, 3, 74);
  add_field("CLCDQ", a, 4, 77);
  add_field("CLCF1", n, 9, 81);
  add_field("CLCF2", n, 9, 90);
  add_field("CLCLC", n, 11,99);
  add_field("CLRTN", n, 9, 110);
  add_field("CLFAT", a, 1, 119);
  add_field("CLFSP", a, 1, 120);
  add_field("CLTPL", a, 2, 121);
}

// TAutomask

class TPaghe2Doc_mask : public TAutomask
{
  void serialize(bool bSave);
protected:
  bool on_field_event(TOperable_field& o, TField_event e, long jolly);
public:
  TPaghe2Doc_mask();
  virtual ~TPaghe2Doc_mask();
};

TPaghe2Doc_mask::TPaghe2Doc_mask() : TAutomask("pg0001100a")
{
  serialize(false);
}

TPaghe2Doc_mask::~TPaghe2Doc_mask()
{
  serialize(true);
}
  
bool TPaghe2Doc_mask::on_field_event(TOperable_field& f, TField_event e, long jolly)
{ 
  return TRUE;
}

void TPaghe2Doc_mask::serialize(bool bSave)
{
  const char* defpar = "MAIN";
  TConfig ini("pg0001conf.ini", defpar);
  for (int i = fields()-1; i >= 0; i--)
  {
    TMask_field& f = fld(i);
    const TFieldref* fr = f.field();
    if (fr != NULL)
    {
      if (bSave)
        fr->write(ini, defpar, f.get());
      else
        f.set(fr->read(ini, defpar));
    }
  }
}

HIDDEN bool browse_file_handler(TMask_field& f, KEY k)
{
  if (k == K_F9)
  {  
    FILE_SPEC fs; memset(&fs, 0, sizeof(FILE_SPEC));
    strcpy(fs.type, "");
    strcpy(fs.name, f.get());
    xvt_fsys_get_default_dir(&fs.dir);
    xvt_fsys_save_dir();
    if (xvt_dm_post_file_open(&fs, TR("Selezione file")) == FL_OK)
    {       
      TFilename n;
      xvt_fsys_convert_dir_to_str(&fs.dir, n.get_buffer(n.size()), n.size());
      n.add(fs.name);
      f.set(n);
    }
    xvt_fsys_restore_dir();
    f.set_focus();
  }
  
  return TRUE;
}

///////////////////////////////////////////////////////////
// TPaghe2Doc application
///////////////////////////////////////////////////////////

class TPaghe2Doc : public TSkeleton_application
{
	TPaghe2Doc_mask*	_m;
  TLog_report*			_log;
  bool							_errors_logged;
	TString8					_codnum, _tipodoc, _tiporiga, _rigadesc;
	TString8					_stato;
	TString80					_descdoc;
	TDate							_datadoc;
	real							_perc;

protected:
	virtual TRecordset& pagheset(const TMask& m);
  virtual const char * extra_modules() const {return "ba";}

public:           
	virtual bool create();
  virtual bool destroy();
  virtual void main_loop();
	void add_testata(const TRecordset& paghe, TConfig& doc);
	void add_riga_doc(const TRecordset& paghe, TConfig& doc, const int nriga, const TString& codivaes);
  TPaghe2Doc() {}
};

TPaghe2Doc& app() { return (TPaghe2Doc&) main_app(); }

                                
bool TPaghe2Doc::create()
{
  _m = new TPaghe2Doc_mask();
	_m->set_handler(F_INPATH, browse_file_handler);
	_m->set_handler(F_INFILE, browse_file_handler);
	return TSkeleton_application::create ();
}

bool TPaghe2Doc::destroy()
{
	delete _m;
  return TApplication::destroy();
}

void TPaghe2Doc::add_testata(const TRecordset& paghe, TConfig& doc)
{
	doc.set_paragraph("Transaction");
	doc.set("Action","INSERT");
	doc.set("Mode","AUTO");
	doc.set_paragraph(format("%d",LF_DOC));
	doc.set(DOC_ANNO, _datadoc.year());
	doc.set(DOC_PROVV, "D");
	doc.set(DOC_CODNUM, _codnum);
	doc.set(DOC_TIPODOC, _tipodoc);
	doc.set(DOC_DATADOC, _datadoc);
	doc.set(DOC_TIPOCF, "C");
	doc.set(DOC_CODCF, paghe.get("CLAZI").as_string());
	doc.set(DOC_STATO, _stato);
	doc.set_paragraph(format("%d,%d",LF_RIGHEDOC, 1));
	doc.set(RDOC_CHECKED, "X");
	doc.set(RDOC_TIPORIGA, _rigadesc);
	doc.set(RDOC_DESCR, _descdoc); // descrizione x fattura
}

void TPaghe2Doc::add_riga_doc(const TRecordset& paghe, TConfig& doc, const int nriga, const TString& codivaes)
{
	doc.set_paragraph(format("%d,%d",LF_RIGHEDOC, nriga));
	doc.set(RDOC_CHECKED, "X");
	doc.set(RDOC_TIPORIGA, _tiporiga);
	const int nrced = paghe.get("CLNCD").as_int(); // numero cedolini
	const real impon = paghe.get("CLILR").as_real() / CENTO; // imponibile
	const TString8 codtri = paghe.get("CLCTR").as_string(); // codice tributo
	const TRectype& recprs = cache().get("PRS", codtri);
	real prezzo = recprs.get_real("R10"); // coefficiente
	if (!_perc.is_zero())
		prezzo+=prezzo*_perc/CENTO;
	const char tipoqta = recprs.get("S6")[0];
	if (tipoqta == 'V')
	{
		prezzo /= CENTO;
		prezzo *= impon;
		doc.set(RDOC_QTA, 1);
	}	
	else
		doc.set(RDOC_QTA, nrced);
	doc.set(RDOC_CODART, codtri);
	doc.set(RDOC_PREZZO, prezzo.string());
	doc.set(RDOC_DESCR, recprs.get("S0")); // descrizione x fattura
	if (codivaes.not_empty())
		doc.set(RDOC_CODIVA, codivaes); // esente
	else
		doc.set(RDOC_CODIVA, recprs.get("S3")); // codice iva
}

TRecordset& TPaghe2Doc::pagheset(const TMask& m)
{
	TString query("SELECT * FROM ");
	TFilename name = m.get(F_INPATH);
	name.add(m.get(F_INFILE));
	query << name;
	TRecordset* paghe = new TPaghe_recset(query);
	return *paghe;
}

void TPaghe2Doc::main_loop()
{
	// eliminazione files delle elaborazioni precedenti
  TString_array transactions;
	TFilename pgfiles; pgfiles.tempdir();
	pgfiles.add("conde*.ini");
  list_files(pgfiles, transactions);
  FOR_EACH_ARRAY_ROW(transactions, row, name)
    remove_file(*name);
	// main
	KEY	tasto;
  tasto = _m->run();
  if (tasto == K_ENTER)
  {
    const char* const title = TR("Importazione documenti da paghe");
    _log = new TLog_report(title);
    _errors_logged = false;
		TRecordset& paghe = pagheset(*_m);
    TProgind pi(paghe.items(), TR("Scansione registrazioni"), true, true);

		TConfig pgconf("pg0001conf.ini");
		_codnum = pgconf.get("CODNUM", "MAIN");
		_tipodoc = pgconf.get("TIPODOC", "MAIN");
		const TString80 str = cache().get("%TIP", _tipodoc, "S2"); // stato inserimento del tipodoc
		_stato = str[0];
		_tiporiga = pgconf.get("TIPORIGA", "MAIN");
		_rigadesc = pgconf.get("RIGADESC", "MAIN");
		_descdoc = _m->get(F_DESCDOC);
		_datadoc = _m->get_date(F_DATADOC);
		_perc = _m->get_real(F_PERC);
		TConfig* docum=NULL;	
		TDocumento* doc=NULL;
		
		bool error = false;
		int ntransac=0; // numero trasnsazione per creare file .ini
		int nriga=0;		// numero riga doc.
		int oldanno = -1;	
		int oldmese = -1;
		long oldcodcf = -1;
    for (bool ok = paghe.move_first(); ok; ok = paghe.move_next())
    {
			bool esente = false;
			TString16 codivaes = "";
      if (!pi.addstatus(1))
        break;
			// non considerare righe con cedolini e imponibile entrambi a zero
			const int nrced = paghe.get("CLNCD").as_int(); // numero cedolini
			const real impon = paghe.get("CLILR").as_real() / CENTO; // imponibile
			if ((nrced != 0) || (!impon.is_zero()))
			{

				const int annocomp = paghe.get("CLA01").as_int();
				const int mesecomp = paghe.get("CLM01").as_int();
				const long codcf   = paghe.get("CLAZI").as_int();
				if ((annocomp != oldanno) || (mesecomp != oldmese) || (codcf != oldcodcf))
				{
					if (docum != NULL)
					{
						delete docum;
						docum = NULL;
					}
					if (error) // cancello il file perch'e la transazione non e' andata bene
					{
						TFilename pgfile; pgfile.tempdir();
						pgfile.add(format("pg000%03d.ini",ntransac));
						if (pgfile.exist())
							remove_file(pgfile);
					}
					oldanno = annocomp;
					oldmese = mesecomp;
					oldcodcf = codcf;
					error = false;
					ntransac++;
					TFilename pgfile; pgfile.tempdir();
					pgfile.add(format("conde%03d.ini",ntransac));
					docum = new TConfig(pgfile);
					add_testata(paghe, *docum);					
					nriga = 1;
					// calcolo se cliente esente
					const long codcli = paghe.get("CLAZI").as_int();
					
					TCli_for& c =   TCli_for('C', codcli);
					TCodiceIVA codes(c.vendite().get(CFV_ASSFIS));
					const TString16 v_esenzione(c.vendite().get(CFV_VSPROT));
					const TString16 v_data_esenzione(c.vendite().get(CFV_VSDATAREG));
					const TString16 n_registrazione(c.vendite().get(CFV_NSPROT)); 
					const TString16 n_data_registrazione(c.vendite().get(CFV_NSDATAREG));
					esente = codes.tipo().not_empty() && v_esenzione.not_empty() &&
												v_data_esenzione.not_empty() && n_registrazione.not_empty() &&  
												n_data_registrazione.not_empty();
					if (esente)
						codivaes = codes.codice();
					else
						codivaes = "";
				}
				nriga++;
				add_riga_doc(paghe, *docum, nriga, codivaes);
			}
		}
		if (docum != NULL)
		{
			delete docum;
			docum = NULL;
		}
		if (error) // cancello il file perch'e la transazione non e' andata bene
		{
			TFilename pgfile; pgfile.tempdir();
			pgfile.add(format("pg000%03d.ini",ntransac));
			if (pgfile.exist())
				remove_file(pgfile);
		}
    TReport_book book;
    book.add(*_log);
    book.preview();

    bool save = true;
    if (_errors_logged)
    {
      save = yesno_box(TR("Sono stati riscontrati uno o piu' errori:\n"
                          "Si desidera creare i documenti ugualmente?"));
    }
    delete _log;
		_log = NULL;
		if (save)
		{
			TString80 applicat;
			applicat.format("ve0.exe -1 -i%s", (const char*) pgfiles);
			TExternal_app gestdoc(applicat);
			gestdoc.run();
		}
  }
}


int pg0001100(int argc, char* argv[])
{
  TPaghe2Doc app;
  app.run(argc, argv, TR("Ricezione fatture da paghe"));
  return TRUE;
}