// Ricezione automatica
                        
#include <applicat.h>
#include <mask.h>
#include <tabutil.h>
#include <utility.h>
#include <config.h>
#include <urldefid.h> 
#include <prefix.h>  
#include <execp.h>     
#include <mailbox.h>

#include "cglib04.h"

class TRic_auto : public TApplication
{                                 
  TTransfer_file* _tras_file;
  
  TString _control_rec, _sigle_file, _nrec_file;
  TDate   _dataultras;    
  int     _nultras;
  long    _ditta;  
  char    _trasfer;
  char    _tipo;
  bool    _cancella_header;
  
public:        
  virtual bool create();
  virtual bool destroy();
  virtual bool menu(MENU_TAG m);         
  virtual bool check_autorization() const 
  {return FALSE;}
  
  bool    main_loop();   
  void    stato_trasferimento(TString& std);
  bool    controlli_preliminari();      
  bool    leggi_trasfer();
  bool    leggi_header(); 
  bool    set_flag();
  
  TRic_auto(const char* ditta, char trasfer, char tipo);
};                                      

HIDDEN TRic_auto& app() { return (TRic_auto &) main_app(); }

TRic_auto::TRic_auto(const char* ditta, char trasfer, char tipo) : 
_ditta(atol(ditta)), _trasfer(trasfer), _tipo(tipo)
{}

void TRic_auto::stato_trasferimento(TString& std)
{
  TConfig conf (CONFIG_DITTA);         // Recupero stato trasferimento
  std = conf.get("FlStTra");           // dai parametri ditta
}
                                   
bool TRic_auto::main_loop()
{ 
  TString std = "";
  
  if (!controlli_preliminari())
    return FALSE;

  set_flag();  
  
  stato_trasferimento(std);
  
  if (std == "T")
  {
     TString appname = "cg6 -5 T A";  // Lancio il programma di ricezione delle tabelle
                                       // con il parametro A perche' si tratta di ricezione
     TExternal_app a (appname);        // in automatico
     a.run();  
  }

  stato_trasferimento(std);                            

  if (std == "C")
  {
     TString appname = "cg6 -6 A ";   // Lancio il programma di lista controllo movimenti
     appname << _tipo;
                                      
     TExternal_app a (appname);       
     a.run();  

     TMailbox m;
     TMessage* msg = m.next_s("");
     int subj;
     
     if (msg != NULL)
     {
       subj = atoi(msg->body()); 
       
       TFilename dirtemp;
       dirtemp.tempdir();
       dirtemp << "cg6700.mbx";
       ::remove(dirtemp);
       
       if (!subj)  
         return FALSE;
     }
  }

  stato_trasferimento(std); 

  if (std == "M")
  {
     TString appname = "cg6 -5 M A";  // Lancio il programma di ricezione dei movimenti
                                       // con il parametro A perche' si tratta di ricezione
     TExternal_app a (appname);        // in automatico
     a.run();  
  }

  stato_trasferimento(std);
  
  if (std == "*")
  {  
    _cancella_header = TRUE;
    _tras_file->remove_all();                        
    TString trasf; 
    trasf = _tras_file->path(_ditta);
    trasf << "\\trasfer";  
    ::remove(trasf);                                                 
    TConfig conf (CONFIG_DITTA);         // Inizializzo stato trasferimento
    conf.set("FlStTra"," ");             // dei parametri ditta
    message_box("Il trasferimento e' stato INTERAMENTE COMPLETATO");
  }

  return FALSE;
}

bool TRic_auto::controlli_preliminari()
{ 
  TString std = "";
                                   
  if (!prefix().exist(_ditta))                                   // Controllo esistenza
    return error_box("Rilevati ERRORI GRAVI nel trasferimento"); // direttorio della ditta

  set_firm(_ditta);
  
  stato_trasferimento(std);
  
  if (std == "")
  {
    if (!leggi_trasfer())                                        // Controllo se esiste il file trasfer
      return error_box("Il file di trasferimento non e' presente nella directory %s",_tras_file->path(_ditta));
      
     TString appname = "cg6 -3 ";                               // Lancio il programma che trasferisce 
     appname << _trasfer << " A";                                // i dati dal trasfer agli archivi temporanei
     
     TExternal_app a (appname);
     a.run();
  }
  
  if (!leggi_header())                                           // Controllo l'esistenza del record
    return error_box("Rilevati ERRORI GRAVI nel trasferimento"); // di controllo nel file header

  TString ult_file = _tras_file->ult_file();
  TString key      = _tras_file->key();
  
  if ( (std != "*" && std != "") || (ult_file != "" || key != "") )
    return error_box("Ultimo trasferimento NON COMPLETATO: completarlo");
  
  if (std == "*")
  {                         
    _cancella_header = TRUE;
    _tras_file->remove_all();                        
    TString trasf; 
    trasf = _tras_file->path(_ditta);
    trasf << "\\trasfer";  
    ::remove(trasf);  
    TConfig conf (CONFIG_DITTA);         // Inizializzo stato trasferimento
    conf.set("FlStTra"," ");             // dei parametri ditta    
  }
                                           
  return TRUE;
}   

bool TRic_auto::leggi_trasfer()
{ 
  TString80 trasf;
  
  trasf = _tras_file->path(_ditta);
  trasf << "\\trasfer";
  
  _tras_file->open(trasf);
  
  if (_tras_file->exist())   
  {
    _tras_file->close();
    return TRUE;        
  }
  
  _tras_file->close();
  
  return FALSE;
}

bool TRic_auto::leggi_header()
{ 
  TString header;
   
  header = _tras_file->path(_ditta);
  header << HEADER;
  
  _tras_file->open(header);
  
  if (_tras_file->exist())           
  {  
    if (_tras_file->read_control_rec())
    {
      _control_rec = _tras_file->record();
      TString tiporecord = _control_rec.sub(0,2);
  
      if (tiporecord != " 1")
        return FALSE;
    }
    else
      return FALSE;
  } 
  else
    return FALSE;
  
  _tras_file->close();
  
  return TRUE; 
}

bool TRic_auto::set_flag()
{
  TString    sigla;
  long       nrec;       
  int        j;                    
  int        k = 0;
  TString    flag;
  TString    record;
  TString    ana_com,pcon_cau;
  TString    uselab;  
  bool       fatto = TRUE;
  
  TConfig conf(CONFIG_DITTA);           
  
  ana_com  = conf.get("AnCfCm","cg");
  pcon_cau = conf.get("PcTcCm","cg");

  TString header;
  header = _tras_file->path(_ditta);
  header << HEADER;
  _tras_file->open(header);
  
  if (_tras_file->exist())
  {  
    if (_tras_file->read_control_rec())
    {                                       
      _nultras    = _tras_file->nultras();
      _dataultras = _tras_file->dataultras();
      _sigle_file = _tras_file->sigle_file();
      _nrec_file  = _tras_file->nrec_file();
      record      = _tras_file->record();   
    }
    
    for (j = 0; j < _sigle_file.len(); j++)
    {                      
      sigla  = _sigle_file.mid(j,1);     
      nrec   = atol(_nrec_file.mid(k,6));
      
      if (fatto)
      {
        if (sigla == "W" || sigla == "P")
        {
          if (nrec > 0 && pcon_cau == "")    
          {
            flag  = "T";
            fatto = FALSE;
          }
        }
        else
          if (sigla == "A")
          {
            if (nrec > 0 && ana_com == "")
            {
              flag  = "T";
              fatto = FALSE;
            }
          }              
          else
            if (sigla == "Z" || sigla == "U" || sigla == "B")
            {
              if (nrec > 0)
              {
                flag  = "C";
                fatto = FALSE;
              }
            }
            else 
            {
              flag = "*";  
              fatto = FALSE;
            }
        
        if (flag == "T")
          uselab = sigla; 
        else 
          uselab = "";                               
      }
      
      if (sigla == "W" || sigla == "P")
      {  
        if (pcon_cau == "X")
        {
          _sigle_file.overwrite(" ",j);   
          _nrec_file.overwrite("000000",k);
        }  
      }
      
      if (sigla == "A")
      {
        if (ana_com == "X")
        {
          _sigle_file.overwrite(" ",j);   
          _nrec_file.overwrite("000000",k);
        }
      }            
      k += 6;
    } 
    
    record.overwrite(_sigle_file,86);
    record.overwrite(_nrec_file,95);
    
    TString agg(7);
    
    agg[0] = ' ';
    agg[1] = 'D';
    agg[2] = 'D';
    agg[3] = 'D';
    agg[4] = ' ';
    agg[5] = ' ';    
    agg[6] = '\0';
    
    record.overwrite(agg,234);
    record.overwrite(uselab,240);  
    TString str;
    str.spaces(60);
    record.overwrite(str,241);
    
    const int size = 1024;
    
    if (!_tras_file->write_control_rec(record, size)) 
      return FALSE;         
    
    _tras_file->close();  
  }  
  
  conf.set("FlStTra", flag);
  
  return TRUE;
}

bool TRic_auto::create()
{
  TApplication::create();  
  
  _cancella_header = FALSE;
  
  _tras_file  = new TTransfer_file(_trasfer);  
  
  dispatch_e_menu (BAR_ITEM(1));

  return TRUE;
}

bool TRic_auto::destroy()
{ 
  delete _tras_file;

  if (_cancella_header)
  {
    TString header;
   
    header = _tras_file->path(_ditta);
    header << HEADER;
   
    ::remove(header);
  }
  
  return TApplication::destroy();
}                                

bool TRic_auto::menu(MENU_TAG m)
{
  if (m == BAR_ITEM(1))
    return main_loop(); 
  return FALSE;
}

int cg6100 (int argc, char* argv[])
{ 
  char p4 = '\0';
  
  if (argc > 5)
    p4 = *argv[4];
          
  TRic_auto* main_app = new TRic_auto(argv[2],*argv[3],p4);       
  main_app->run(argc, argv,"Ricezione automatica");
  delete main_app;
  return TRUE;
}