#include <applicat.h>
#include <automask.h>
#include <defmask.h>
#include <golem.h>
#include <modaut.h>
#include <progind.h>
#include <reputils.h>
#include <textset.h>
#include <utility.h>

#include "pg0067100a.h"




///////////////////////////////////////////////
//  MASCHERA
///////////////////////////////////////////////
class TDistribuzione_f24_mask : public TAutomask
{
protected:
  TRecordset* create_recordset() const;
  void print_stats(const bool stampa) const;
  void export_stats() const;
  virtual bool on_field_event(TOperable_field& o, TField_event e, long jolly);

public:
  TDistribuzione_f24_mask();
};

TDistribuzione_f24_mask::TDistribuzione_f24_mask() : TAutomask("pg0067100a")
{
}

bool TDistribuzione_f24_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
{
  switch(o.dlg())
  {
    case DLG_PRINT: //stampa
    if (e == fe_button)
    {
      print_stats(true);
    }
    break;
    case DLG_PREVIEW: //stampa
    if (e == fe_button)
    {
      print_stats(false);
    }
    break;
    case DLG_EXPORT:  //esporta in excel
    if (e == fe_button)
    {
      export_stats();
    }
    break;
  default:
    break;
  }
  return true;
}

//metodo comune di generazione del recordset
//recordset che deve ordinare, per piva e anno, i files pdf che trova nelle sottocartelle della..
//..cartella radice di destinazione
TRecordset* TDistribuzione_f24_mask::create_recordset() const
{
  TAS400_recordset* recset = new TAS400_recordset("AS400(58)");
  recset->create_field("CODICE_FISCALE", 0, 16, _alfafld, true);
  for (int j = 2006; j < 2016; j++)
  {
    TString8 anno;
    anno << "F24_" << j;
    recset->create_field(anno, -1, 4, _intfld, true);
  }
  recset->create_field("CR", -1, 2, _alfafld, true, TVariant("\n\r"));

  //cartella radice di destinazione
  const TString& dest_dir = get(F_PATH_DST);
  TFilename dest_pivas = dest_dir; dest_pivas.add("*");
  SLIST pivas = xvt_fsys_list_files(DIR_TYPE, dest_pivas, true);
  for (SLIST_ELT e = xvt_slist_get_first(pivas); e; e = xvt_slist_get_next(pivas, e))
  { 
    TFilename dest_years = xvt_slist_get(pivas, e, NULL);
    const TString& piva = dest_years.name_only();
    if (piva.len() < 11 || piva.len() > 16)
      continue;

    recset->new_rec("");
    recset->set("CODICE_FISCALE", piva);

    dest_years.add("20??");
    SLIST years = xvt_fsys_list_files(DIR_TYPE, dest_years, true);
    for (SLIST_ELT e = xvt_slist_get_first(years); e; e = xvt_slist_get_next(years, e))
    {
      TFilename dest_year = xvt_slist_get(years, e, NULL);
      const TString4 year = dest_year.name_only();
      dest_year.add("*.pdf");
      SLIST files = xvt_fsys_list_files("", dest_year, false);
      const long count = xvt_slist_count(files);
      xvt_slist_destroy(files);

      //aggiunge la riga al recordset
      TString8 fld; fld << "F24_" << year;
      recset->set(fld, count);
    }
    xvt_slist_destroy(years);
  }
  xvt_slist_destroy(pivas);

  //ordina il recordset per cofi/piva
  recset->sort();
  return recset;
}

void TDistribuzione_f24_mask::print_stats(const bool stampa) const
{
  TRecordset* recset = create_recordset();
  TReport rep;
  rep.load("pg0067100");
  rep.set_recordset(recset);
  if (stampa)
    rep.print();
  else
    rep.preview();
}

void TDistribuzione_f24_mask::export_stats() const
{
  TRecordset* recset = create_recordset();
  TFilename temp;
  temp.temp("", "xls");
  if (recset->save_as(temp, fmt_html))
    goto_url(temp);
  delete recset;
}


//////////////////////////////////////////////
//  APPLICAZIONE
/////////////////////////////////////////////
//Ridistributore di F24 per il computer
class TDistribuzione_f24 : public TSkeleton_application
{
  TDistribuzione_f24_mask*  _mask;

  virtual bool check_autorization() const {return false;}
  
protected:
  virtual const char * extra_modules() const {return "rs";}
  virtual bool create();

  void elabora();

public:
  virtual void main_loop();
};

void TDistribuzione_f24::elabora()
{
  TFilename src_files = _mask->get(F_PATH_SRC);
  src_files.add("*.pdf");
  TString_array src_files_list;
  //dalla cartella origine prende tutti i files .pdf e crea una simpatica lista
  const int n_files_pdf = list_files(src_files, src_files_list);

  const TString& dst_root_path = _mask->get(F_PATH_DST);
  const bool delete_src_files = _mask->get_bool(F_ERASE_TRANSFERRED);

  //scansione dello string_array per il trasferimento (con tanto di progind e log)
  TProgind pi(n_files_pdf, TR("Trasferimento F24 in corso..."), true, true);
  TLog_report log("ERRORI DI TRASFERIMENTO");

  TToken_string curr_tok_file(_MAX_PATH, '_');

  for (int i = 0; i < n_files_pdf; i++)
  {
    if (!pi.addstatus(1))
      break;

    //file in formato filename e token_string (per prendere i pezzi)
    const TFilename curr_fname = src_files_list.row(i);
    curr_tok_file = curr_fname.name_only();

    //anno e relativo controllo
    const int anno = curr_tok_file.get_int(0);
    if (anno < 2000)
    {
      TString msg;
      msg.format("File %s ha ANNO errato", (const char*)curr_tok_file);
      log.log(1, msg);
      continue;
    }

    //piva e relativo controllo
    const TString16 piva = curr_tok_file.get(1);
    if (piva.len() < 11)
    {
      TString msg;
      msg.format("File %s ha P.IVA o C.F. errato", (const char*)curr_tok_file);
      log.log(1, msg);
      continue;
    }

    //controllo della cartella di destinazione
    TFilename dst_file = dst_root_path;
    dst_file.add(piva);
    TString4 str_anno;
    str_anno << anno;
    dst_file.add(str_anno);
    const bool crea_dir = make_dir(dst_file);
    //non riesce a crearla! deve dare errore di grave livello!
    if (!crea_dir)
    {
      TString msg;
      msg.format("Impossibile creare la cartella %s !", dst_file);
      log.log(2, msg);
      continue;
    }

    //se invece crea/trova la cartella -> copia il file
    dst_file.add(curr_fname.name());

    const bool copia_riuscita = fcopy(curr_fname, dst_file);
    if (!copia_riuscita)
    {
      TString msg;
      msg.format("Impossibile copiare il file %s !", curr_fname.name());
      log.log(2, msg);
      continue;
    }

    //controllo dell'avvenuta copia e della correttezza del file destinazione
    //controllo sulle dimensioni
    const long src_size = fsize(curr_fname);
    const long dst_size = fsize(dst_file);

    if (src_size != dst_size)
    {
      TString msg;
      msg.format("Copia del file %s non completata !", curr_fname.name());
      log.log(2, msg);
      continue;
    }

    //eliminazione del file sorgente
    if (delete_src_files)
    {
      const bool src_file_removed = remove_file(curr_fname);
      if (!src_file_removed)
      {
        TString msg;
        msg.format("Impossibile eliminare il file origine %s ", curr_fname.name());
        log.log(1, msg);
        continue;
      }
    }
  } //for(int i...

  message_box(TR("Elaborazione completata"));

  const int items = log.recordset()->items();
  if (items > 0)
    log.preview();
}

bool TDistribuzione_f24::create()
{
    //se non ha il modulo RS non pu� proseguire
  if (!has_module(RSAUT))
    return error_box(TR("Modulo non autorizzato"));

  return TSkeleton_application::create();
}

void TDistribuzione_f24::main_loop()
{
  _mask = new TDistribuzione_f24_mask;
  if (_mask->run() != K_QUIT)
    elabora();

  delete _mask;
  _mask = NULL;
}

int pg0067100 (int argc, char **argv)
{
  TDistribuzione_f24 a;
  a.run(argc,argv, TR("Archiviazione F24"));
  return true;
}