// Importazione paghe consorzio isologistica

#include <applicat.h>
#include <automask.h>
#include <config.h>
#include <execp.h>
#include <filetext.h>
#include <progind.h>
#include <recarray.h>
#include <strings.h>
#include <utility.h>

#include "../cg/cglib01.h"
#include "ps0913.h"
#include "ps0913100a.h"
#include "ps0913100b.h"
#include "ps0913100c.h"

#include <causali.h>
#include <mov.h>
#include <pconti.h>
#include <rmov.h>

#define MAX_CG_ROWS 98


// TAutomask

class TImpPaghe_mask : public TAutomask
{
protected:
  bool on_field_event(TOperable_field& o, TField_event e, long jolly);
public:
  TImpPaghe_mask();
  virtual ~TImpPaghe_mask(){};
};
  
TImpPaghe_mask::TImpPaghe_mask() :TAutomask ("ps0913100a")
{
}  

bool TImpPaghe_mask::on_field_event(TOperable_field& f, TField_event e, long jolly)
{ 
  switch (f.dlg())
  { 
  case F_CODDITTA:            
    if (e == fe_modify)
    {
			const long firm = atol(f.get());
			if (firm > 0)
				main_app().set_firm(firm);
		}
	break;
	default:
	break;	
	}
  return TRUE;
}


// TFile_text

class TImpPaghe_file: public TFile_text
{ 
protected:
  virtual void validate(TCursor& cur,TRecord_text &rec, TToken_string &val, TString& str);

public:
  TImpPaghe_file(const TString& file_name);
  virtual ~TImpPaghe_file() { }
};

TImpPaghe_file::TImpPaghe_file(const TString& file_name)
          : TFile_text(file_name, "ps0913100.ini")
{
}

void TImpPaghe_file::validate(TCursor& cur,TRecord_text &rec, TToken_string &s, TString& str)
{
  const TString code(s.get(0));
  TString valore = str;
  if (code == "_UPPERCASE")
  {
    valore.upper(); 
  }
  if (code == "_STRIP")
  {
    valore.strip("#"); 
  }
  if (code == "_IMPORTO")
  {
    real importo(valore);
		importo = importo/100;
		valore = importo.string(2);
  }
  else NFCHECK("Macro non definita: %s", (const char *)code);
  str = valore;
} 

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());
    //strcpy(fs.creator, "ba1");
    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;
}

// TSkeleton_application

class TImpPaghe : public TSkeleton_application
{
	TImpPaghe_mask*		_msk;
	TImpPaghe_file*    _trasfile;
	TConfig*		    _configfile;
  TRelation*      _rel;
  TCursor*        _cur;
  TProgind*       _prog;  
  TEsercizi_contabili* _esc;
  long    _numreg;

	virtual bool check_autorization() const {return false;}
  virtual const char * extra_modules() const {return "cg";}

public:           
  virtual bool create();
  virtual bool destroy();
  virtual void main_loop();
  //virtual void ini2mask();
  //virtual void mask2ini();
	bool transfer();
  int  strip_zero(TString& importo);
  bool my_isdigit(unsigned char ch);
 
  TImpPaghe() {}
};

TImpPaghe& app() { return (TImpPaghe&) main_app(); }
                                      
bool TImpPaghe::create()
{
  open_files(LF_TABCOM, LF_TAB, LF_PCON, LF_MOV, LF_RMOV, LF_RMOVIVA, 0);
	TFilename configname = "ps0913100a.ini";
	configname.custom_path();
  _configfile = new TConfig(configname);
  _msk = new TImpPaghe_mask();
	_msk->set_handler(F_PERCORSO, browse_file_handler);
	_rel   = new TRelation (LF_PCON);
  _cur   = new TCursor(_rel,"((GRUPPO!=\"\")&&(CONTO!=\"\")&&(SOTTOCONTO==\"\"))",1);
	_esc   = new TEsercizi_contabili;
         
  return TSkeleton_application::create();
}

bool TImpPaghe::destroy()
{
  delete _esc;
  delete _cur;
  delete _rel;
	delete _msk;
	delete _configfile;
  
  return TApplication::destroy();
}

/*
void TImpPaghe::mask2ini()
{
	TSheet_field& sheet = (TSheet_field&)_msk->field(F_SHEET_CONTI);
	for (int i=0;i<sheet.items();i++)
	{
		TToken_string& row = sheet.row(i);
		TString16 contoorigine = row.get(0);
		TString16 conto;
		const int gr = atoi(row.get(1));
		const int co = atoi(row.get(2));
		const long so = atol(row.get(3));
		conto.format("%d|%d|%ld", gr, co, so);
		_configfile->set(contoorigine, conto, "CONTI");
	}
	TSheet_field& sheetcms = (TSheet_field&)_msk->field(F_SHEET_CMS);
	for (i=0;i<sheetcms.items();i++)
	{
		TToken_string& row = sheetcms.row(i);
		TString16 cmsorigine = row.get(0);
		TString80 cms = row.get(1);
		_configfile->set(cmsorigine, cms, "COMMESSE");
	}
	_configfile->set_paragraph("CONTI");
}

void TImpPaghe::ini2mask()
{
	TString_array vl;
	_configfile->list_variables(vl,TRUE, "CONTI", TRUE);
	TSheet_field& sheet = (TSheet_field&)_msk->field(F_SHEET_CONTI);
	sheet.destroy();
	int i=0;
	FOR_EACH_ARRAY_ROW(vl,r,s)
	{
		TToken_string& riga = sheet.row(i);
		TString16 contoorigine = (*s).get();
		TToken_string conto = _configfile->get(contoorigine, "CONTI");
		riga.add(contoorigine);
		riga.add(conto.get(0));
		riga.add(conto.get(1));
		riga.add(conto.get(2));
		sheet.check_row(i);
		i++;
	}
	_configfile->list_variables(vl,TRUE, "COMMESSE", TRUE);
	TSheet_field& sheetcms = (TSheet_field&)_msk->field(F_SHEET_CMS);
	sheetcms.destroy();
	i=0;
	FOR_EACH_ARRAY_ROW(vl,rc,sc)
	{
		TToken_string& riga = sheetcms.row(i);
		TString16 cmsorigine = (*sc).get();
		TString80 cms = (*sc).get();
		riga.add(cmsorigine);
		riga.add(cms);
		sheetcms.check_row(i);
		i++;
	}
}

	*/
void TImpPaghe::main_loop()
{
  KEY	tasto;
  _msk->set(F_PERCORSO,	_configfile->get("PERCORSO", "MAIN"));
  _msk->set(F_CODCAUS,	_configfile->get("CODCAUS", "MOVIMENTO"));
	//ini2mask();
  tasto = _msk->run();
  if (tasto == K_ENTER)
  {
		//mask2ini();
    _numreg = 0;
		if (transfer())
		{
			_configfile->set("PERCORSO", _msk->get(F_PERCORSO), "MAIN");
			_configfile->set("CODCAUS", _msk->get(F_CODCAUS), "MOVIMENTO");
			message_box(TR("Importazione stipendi completata"));
		}
  }   
}

bool TImpPaghe::transfer()
{
	TString_array transactions;
	TFilename tempdir;
	tempdir.tempdir();

	TString80 listfiles = tempdir;
	listfiles << "\\oo*.ini";
  list_files(listfiles, transactions);
  FOR_EACH_ARRAY_ROW(transactions, row, name)
    remove(*name);

	TConfig* movpn=NULL;

  _trasfile = new TImpPaghe_file(_msk->get(F_PERCORSO));
  _trasfile->open(_msk->get(F_PERCORSO),'r');

	// creazione file temporanei per commessa e conto dare e avere
  const long dimension = fsize(_msk->get(F_PERCORSO));
  TProgind pi(dimension,"Importazione in corso...");

  TRecord_text curr;
  while (_trasfile->read(curr) == NOERR) 
  {
    pi.setstatus(_trasfile->read_file()->tellg());
		TString impstr = curr.get(F_IMPORTO);
		real importo(impstr);
		importo = importo/100;
		const char sezione = curr.get(F_SEZIONE)[0];
		const TString16 gruppo = curr.get(F_GRUPPOP);
		const TString16 conto = curr.get(F_CONTOP);
		const TString16 sottoconto = curr.get(F_SOTTOCONTOP);
		TString16 contomov;
		TString80 codcmsnozf;
		contomov.format("%3s%3s%6s", (const char*) gruppo, (const char*) conto, (const char*) sottoconto);

		if ((!real::is_null(impstr)) && (!contomov.blank()))
		{
			TString16 codcms = curr.get(F_COMMESSA);
			codcms.trim();
			codcms.strip("#");
			TString16 fasecms = curr.get(F_FASE);
			fasecms.trim();
			fasecms.strip("#");
			codcms << fasecms;
			TString80 cms = _configfile->get(codcms, "COMMESSE");
			if (cms.empty())
				_configfile->set(codcmsnozf, codcms, "COMMESSE");
			TFilename name;
			name.tempdir();
			name.add(format("oo%s", (const char*) codcms));
			name.ext(".ini");
			movpn = new TConfig(name);
			movpn->set_paragraph("MAIN");
			movpn->set("CODCMS",codcms);
			if (sezione == 'D') // dare
			{
				movpn->set_paragraph("IMPORTI");
				contomov.trim();
				impstr = movpn->get(contomov, "IMPORTI");
				real importomem(impstr);
				importomem+=importo;
				movpn->set(contomov, importomem.string());
			}
			else // avere
			{
				movpn->set_paragraph("IMPORTI");
				contomov.trim();
				impstr = movpn->get(contomov, "IMPORTI");
				real importomem(impstr);
				importomem-=importo;
				movpn->set(contomov, importomem.string());
			}
			delete movpn;
			if (pi.iscancelled())
				return TRUE;
		}
	}
  _trasfile->close();
	delete _trasfile;

	// creazione .ini per la prima nota
	const TDate datareg = _msk->get_date(F_DATAREG);
	const int annoes = _esc->date2esc(datareg);
	const TString8 codcaus = _msk->get(F_CODCAUS);

	listfiles = tempdir;
	listfiles << "\\oo*.ini";
  list_files(listfiles, transactions);
  FOR_EACH_ARRAY_ROW(transactions, row_oo, name_oo)
	{
	  TConfig* movpn=NULL;
		TConfig file_oo(*name_oo);
		TString16 codcms = file_oo.get("CODCMS", "MAIN");
		codcms.trim();
		TFilename name;
		name.tempdir();
		name.add(format("ooo%s", (const char*) codcms));
		name.ext(".ini");
		movpn = new TConfig(name);

		movpn->set_paragraph("Transaction");
		movpn->set("Action","INSERT");
		movpn->set("Mode","AUTO");
 
		movpn->set_paragraph(format("%d",LF_MOV));
		movpn->set("ANNOES", annoes);
		movpn->set("DATACOMP", datareg);
		movpn->set("DATAREG", datareg);
		movpn->set("DESCR", cache().get(LF_CAUSALI, codcaus, CAU_DESCR));
		movpn->set("CODCAUS", codcaus);
		
		int numrig = 0;
		
		TString_array vl;
	  file_oo.list_variables(vl,TRUE, "IMPORTI", TRUE);
		FOR_EACH_ARRAY_ROW(vl,r,s)
		{
			TString16 contoorigine = (*s).get();
			TString16 importos = (*s).get();
			TToken_string conto = _configfile->get(contoorigine, "CONTI");
			if (conto.empty())
			{
				TString80 contonostro(contoorigine);
				contonostro.insert("|",6);
				contonostro.insert("|",3);
				_configfile->set(contoorigine, contonostro, "CONTI");
				conto = contonostro;
			}
			numrig++;
			movpn->set_paragraph(format("%d,%d",LF_RMOV, numrig));
			movpn->set("ANNOES", annoes);
			movpn->set("DATAREG", datareg);
			movpn->set("NUMRIG", numrig);
			real importo(importos);
			if (importo > 0)
				movpn->set("SEZIONE", "D");
			else
				movpn->set("SEZIONE", "A");
			importos.strip("-");
			movpn->set("IMPORTO", importos);
			//TString16 contoindbil;
			//contoindbil.format("%s|%s", conto.get(0), conto.get(1));
			//const char indbil = cache().get(LF_PCON, contoindbil, PCN_INDBIL)[0]; 
			//if ((indbil != '1') && (indbil != '2'))
			//{
				TString str;
				TString80 commessa = _configfile->get(codcms, "COMMESSE");
				TString80 fase = commessa.mid(3,3);
				commessa = commessa.mid(0,3);
				if (commessa.not_empty() && real::is_natural(commessa))
				{
					str.format("%020s", (const char*) commessa);
					commessa = str;
				}
				if (fase.not_empty() && real::is_natural(fase))
				{
					str.format("%010s", (const char*) fase);
					fase = str;
				}
				movpn->set("CODCMS", commessa);
				movpn->set("FASCMS", fase);
			//}
			movpn->set("GRUPPO", conto.get(0));
			movpn->set("CONTO", conto.get(1));
			movpn->set("SOTTOCONTO", conto.get(2));
		}
		delete movpn;
	}
	
	tempdir.tempdir();
	TString80 applicat = "cg2.exe -0 -i";
	applicat << tempdir;
	applicat << "\\ooo*.ini";
	TExternal_app primanota(applicat);
  primanota.run();
	
	listfiles = tempdir;
	listfiles << "\\oo*.ini";
  list_files(listfiles, transactions);
  FOR_EACH_ARRAY_ROW(transactions, rowf, namef)
		remove(*namef);
	return TRUE;
}

int ps0913100 (int argc, char* argv[])
{
  TImpPaghe main_app;
  main_app.run(argc, argv, TR("Importazione paghe"));
  return TRUE;
}