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

#include "tabutil.h"

#include "ps0713.h"
#include "ps0713200a.h"



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

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

public:
  TImportaComm_mask();
};
  
TImportaComm_mask::TImportaComm_mask() :TAutomask ("ps0713200a")
{
}  

bool TImportaComm_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("*.csv");	//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 TCommCSV : public TSkeleton_application
{
  virtual bool check_autorization() const {return false;}
  virtual const char * extra_modules() const {return "cg";}

	TImportaComm_mask*				_msk;
	TConfig*							    _configfile;

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

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

/////////////////////////////////
//		inserimento commesse
/////////////////////////////////

bool TCommCSV::transfer(const TFilename& file)
{
  TLog_report log("Inserimento Commesse");

  TToken_string rec(50,',');

  TScanner s(file);
  rec = s.line();
  
  
  TTable comm("CMS");
  
  TProgind pi(fsize(file),"Inserimento Commesse in corso...",true,true);

  while (s.ok())
  {
    if (!pi.addstatus(s.tellg())) 
      break;   

    TString str = "La commessa ";
    TString codtab = rec.get(0);
    codtab.strip("\"");

    //salto le righe vuote del file
    if (codtab.empty())
      continue;

    comm.zero();
    comm.put("CODTAB", codtab); //setto il campo CODTAB
    
    TString tmp = "IDLAVORO ";
    tmp << codtab;

    comm.put("S0", tmp);  //setto il campo descrizione (S0)

    TString gr = rec.get(1);
    gr.strip("\"");
    TString co = rec.get(2);
    co.strip("\"");
    TString sc = rec.get(3);
    sc.strip("\"");

    //inserisco il gruppo, il conto e il sottoconto
    //solo se esistono e/o hanno valori sensati
    if (gr == "" || gr == "?")
      gr = "0";

    comm.put("I1", gr);
    
    if (co == "" || co == "?")
      co = "0";
      
    comm.put("I2", co);

    if (sc == "" || sc == "?")
      sc = "0";

    comm.put("I3", sc);

    int err = comm.write();

    if (err == NOERR)
    {
      str << codtab << " � stata inserita";
      log.log(0, str);
    }
    else
    {
      if (err == 224)
        str << codtab << " NON � stata inserita perch� esiste gi�";
      else
        str << codtab << " NON � stata inserita. Errore = " << err;

      log.log(2, str);
    }

    rec = s.line();

  }

  TReport_book buc;
	buc.add(log);
	buc.preview();

  return true;
}

void TCommCSV::mask2ini()
{
	//carica i parametri del file di configurazione
	_configfile->set_paragraph("MAIN");
  for (int i = 0; i < _msk->fields() ; i++)
	{
		TMask_field& f = _msk->fld(i);
		const TFieldref* fr = f.field();
		if (fr != NULL)
			_configfile->set(fr->name(), f.get());
	}
}

void TCommCSV::ini2mask()
{
	//carica i parametri del file di configurazione
	_configfile->set_paragraph("MAIN");
  for (int i = 0; i < _msk->fields() ; i++)
	{
		TMask_field& f = _msk->fld(i);
		const TFieldref* fr = f.field();
		if (fr != NULL)
			f.set(_configfile->get(fr->name()));
	}
}

bool TCommCSV::create()
{
  _configfile = new TConfig("ps0713conf.ini");
  _msk = new TImportaComm_mask();

         
  return TSkeleton_application::create();
}

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

void TCommCSV::main_loop()
{
  KEY	tasto;
	ini2mask();
  tasto = _msk->run();
  if (tasto == K_ENTER)
  {
		mask2ini();

    //genero il nome del file da caricare
    TFilename name = _msk->get(F_PATH);
    name.add(_msk->get(F_NAME));
		if (transfer(name))
		{
			message_box(TR("Importazione documenti completata"));
		}
  }   
}

int ps0713200 (int argc, char* argv[])
{
  TCommCSV main_app;
  main_app.run(argc, argv, TR("Importazione Commesse"));
  return true;
}