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

#include "../ce/ammce.h"
#include "../ce/cespi.h"
#include "../ce/salce.h"

#include "../cg/cglib01.h"

#include "lv4.h"
#include "lv4100.h"
#include "lv4300a.h"

#define CGC_DITTA								 0
#define CGC_GRUPPO							 1
#define CGC_SPECIE							 2
#define CGC_CESPITE							 3
#define CGC_CODPADRE						 4
#define CGC_CEINCR							 5
#define CGC_NPROGR							 6
#define CGC_DESCR								 7
#define CGC_CEALIQ1							 8
#define CGC_PERCAMMANTIC				 9
#define CGC_COSTOACQ						10
#define CGC_COSTODAAMM					11
#define CGC_RIVALUTAZIONE				12
#define CGC_RETTIFICHE					13
#define CGC_FONDOAMMORT					14
#define CGC_TOTAMMANTIC					15
#define CGC_RIVALUTAMM					16
#define CGC_CEDIMRIVALUTAMM     17
#define CGC_AMMORTINDEDUCIBILE	18
#define CGC_CREDIMPOSTA					19
#define CGC_VENDCOSTOACQ				20
#define CGC_VENDFDOAMM					21
#define CGC_PLUSREINVEST				22
#define CGC_VALORVEN						23
#define CGC_DATAINIZAMM					24
#define CGC_DATAACCANTONAM			25
#define CGC_DATAALIENAZIONE     26
#define CGC_PERCDAAMM						27
#define CGC_RIFERFATTVEN				28
#define CGC_RIFERFATTACQ				29
#define CGC_CODFOR							30
#define CGC_CEDITFIL						31
#define CGC_RIFERACQ						32
#define CGC_CODCLI							33
#define CGC_INAMMCOSTOES				34
#define CGC_IMMATERIALI					35
#define CGC_TIPOAMMORT					36
#define CGC_CESSIONE						37
#define CGC_RIFERVEN						38
#define CGC_CEMANRIP						39
#define CGC_PERCAMMSTD					40
#define CGC_NQUOTEANTCALC				41
#define CGC_NUMMOVCESP					42
#define CGC_VENDFDOANT					43
#define CGC_AMMDIPPADRE					44

///////////////////////////////////////////////////////////
// TAutomask
///////////////////////////////////////////////////////////

class TImporta_cesp_mask : public TAutomask
{
protected:
  virtual bool on_field_event(TOperable_field& o, TField_event e, long jolly);

public:
  TImporta_cesp_mask();
};
  
TImporta_cesp_mask::TImporta_cesp_mask() :TAutomask ("lv4300a")
{
}  

bool TImporta_cesp_mask::on_field_event(TOperable_field& f, TField_event e, long jolly)
{ 
	switch (f.dlg())
	{
		//giochetto per avere la lista dei files validi nella directory di trasferimento!
		case F_NAME:
			if (e == fe_button)
			{
				TArray_sheet as(-1, -1, 72, 20, TR("Selezione file"), 
                           "File@32");
				TFilename path = get(F_PATH);
				path.add("*.txt");	//files delle testate
				list_files(path, as.rows_array());
				TFilename name;
				FOR_EACH_ARRAY_ROW(as.rows_array(), i, row)
				{
					name = *row;
					*row = name.name();
				}
				if (as.run() == K_ENTER)
				{
					f.set(as.row(as.selected()));
				}
			}
			break;
		default:
			break;
	}
  return true;
}


///////////////////////////////////////
// TSkeleton_application
///////////////////////////////////////
class TImporta_cesp : public TSkeleton_application
{
	TImporta_cesp_mask*	_msk;

protected:
	bool log_error(TLog_report& log, const char* msg, const TRecordset& recset, const int err=NOERR);
	bool search_gr_sp_ca(const int gruppo, const char* specie, const int categoria);

public:           
  virtual bool create();
  virtual bool destroy();
  virtual void main_loop();
	void transfer(const TFilename& file);
};

bool TImporta_cesp::search_gr_sp_ca(const int gruppo, const char* specie, const int categoria)
{
	return true;
}

bool TImporta_cesp::log_error(TLog_report& log, const char* msg, const TRecordset& recset, const int err)
{
  TString message;
  message << recset.get(CGC_CESPITE) << ' ' << recset.get(CGC_DESCR)
					<< " : " << msg << err;
  log.log(2, message);
  return false;
}

void TImporta_cesp::transfer(const TFilename& file)
{
	TImporta_cogeco_recset recset(file);
  TString caption; _msk->get_caption(caption);
  TProgind pi(recset.items(), caption, true, true);
	const long ditta = _msk->get_long(F_CODITTA);
	const TEsercizi_contabili esc;
	int lastesc = esc.last(); // uso ultimo esercizio contabile
	long ntran = 1;
  TLog_report log(caption);
  TLocalisamfile cespi(LF_CESPI);
	TLocalisamfile salce(LF_SALCE);
	TLocalisamfile ammce(LF_AMMCE);
  for (bool ok = recset.move_to(1); ok ; ok = recset.move_next())
  {
    if (!pi.addstatus(1)) 
      break;
		
		const long dt = recset.get(CGC_DITTA).as_int();

		if (ditta != dt)
			continue;

		TString16 codces = recset.get(CGC_NPROGR).as_string();
		codces.right_just(10, '0');
		// verifico il codice cespite padre
		TString16 codpadre = recset.get(CGC_CODPADRE).as_string();
    codpadre.right_just(10, '0');

    if (real::is_null(codpadre)) // nuovo cespite
		{
			// creo record anagrafica cespi
			cespi.zero();
			cespi.put(CESPI_IDCESPITE, codces);
			const int gr = recset.get(CGC_GRUPPO).as_int();
			const TString4 sp = recset.get(CGC_SPECIE).as_string();
			const int ca = recset.get(CGC_CESPITE).as_int();

			if (search_gr_sp_ca(gr, sp, ca))
			{
				cespi.put(CESPI_CODCGRA, gr);
				cespi.put(CESPI_CODSPA, sp);
				cespi.put(CESPI_CODCAT, ca);
				cespi.put(CESPI_CODCGR, gr);
				cespi.put(CESPI_CODSP, sp);
				cespi.put(CESPI_DESC, recset.get(CGC_DESCR).as_string());
				if (TDate::isdate(recset.get(CGC_DATAINIZAMM).as_string()))
				{
					TDate data(recset.get(CGC_DATAINIZAMM).as_string());
					cespi.put(CESPI_DTFUNZ, data);
					cespi.put(CESPI_DTCOMP, data);
				}
				if (TDate::isdate(recset.get(CGC_DATAALIENAZIONE).as_string()))
				{
					TDate data(recset.get(CGC_DATAALIENAZIONE).as_string());
					cespi.put(CESPI_DTALIEN, data);
				}
				cespi.put(CESPI_TPSPEMAN, 1);
				cespi.put(CESPI_FLGTPVEI, 1);

				// scrivo i record dei cespiti
				int err = cespi.write();
				if (err != NOERR)
					log_error(log, TR("Errore in scrittura anagrafica cespiti "), recset, err);
				else
				{
					// creo record salce
					salce.zero();
					salce.put(SALCE_IDCESPITE, cespi.get(CESPI_IDCESPITE));
					salce.put(SALCE_CODES, lastesc); // ultimo esercizio
					salce.put(SALCE_TPSALDO, 1); // saldo iniziale
					salce.put(SALCE_NUMELE, 1);
					salce.put(SALCE_CSTO, recset.get_real(CGC_COSTOACQ));
					salce.put(SALCE_NUMELE, 1);
					salce.put(SALCE_ANNIAMM, 1);
					err = salce.write();
					if (err != NOERR)
						log_error(log, TR("Errore in scrittura saldi cespiti "), recset, err);
					else
					{
						// creo i records ammce
						for (int i=1; i<=3; i++)
						{
							ammce.zero();
							ammce.put(AMMCE_IDCESPITE, salce.get(CESPI_IDCESPITE));
							ammce.put(AMMCE_CODES, salce.get(SALCE_CODES)); 
							ammce.put(AMMCE_TPSALDO, salce.get(SALCE_TPSALDO)); 
							ammce.put(AMMCE_TPAMM, i); // creo i tre tipi di ammortamento 
							ammce.put(AMMCE_QNOR, recset.get_real(CGC_FONDOAMMORT));
							ammce.put(AMMCE_QANT, recset.get_real(CGC_TOTAMMANTIC));
							err = ammce.write();
							if (err != NOERR)
								log_error(log, TR("Errore in scrittura ammortamento cespiti "), recset, err);
						}
					}
				}
			}
		}
		else
		{
			cespi.zero();
			cespi.put(CESPI_IDCESPITE, codpadre);
			int err = cespi.read();
			if (err == NOERR)
			{
				TString256 descr = cespi.get(CESPI_DESC);
				descr << '+' << recset.get(CGC_DESCR).as_string();
				descr.cut(60);
				cespi.put(CESPI_DESC, descr);
				cespi.write();
			}
			else
				log_error(log, TR("Errore nel cespite padre "), recset, err);
		}
	}
  if (log.recordset()->items() > 0)
    log.preview();
}

bool TImporta_cesp::create()
{
  _msk = new TImporta_cesp_mask();       
  return TSkeleton_application::create();
}

bool TImporta_cesp::destroy()
{
	delete _msk;
  return TApplication::destroy();
}

void TImporta_cesp::main_loop()
{
  KEY	tasto;
	tasto = _msk->run();
  if (tasto == K_ENTER)
  {
    //genero il nome del file da caricare
    TFilename name = _msk->get(F_PATH);
    name.add(_msk->get(F_NAME));
		transfer(name);
  }   
}

int lv4300 (int argc, char* argv[])
{
  TImporta_cesp main_app;
  main_app.run(argc, argv, TR("Importazione cespiti COGECO"));
  return true;
}