#include <inst.h>
#include <config.h>
#include <prefix.h>
#include <progind.h>
#include "..\ba\bainsta.h"

// ********************************
// classe TSystemtempfile
// ********************************


// classe provvisoria per i system file temporanei, ovvero file temporanei con
// caricamento/scaricamento
// @doc EXTERNAL

// @mfunc Importa un file ascii
//
// @rdesc Ritorna NOERR se l'operazione di lettura e' riuscita, altrimenti il codice di
//    di errore generato (vedi <t TIsamerr>).
int TSystemtempfile::load(
    const char* from, // @parm Nome del file da importare 
    char fs,    // @parm Carattere separatore di campo (default <pipe>)
    char fd,            // @parm Carattere delimitatore di campi (default '\\0')
    char rs,            // @parm Carattere separatore di record (default '\\n')
    bool vis,     // @parm Indica se visualizzare lo stato dell'operazione (default TRUE)
    bool extended)  // @parm Indica se interpretare alcune stringhe come macro (default FALSE)
    
// @comm Se <p extended> e' TRUE e trova alcune stringhe col formato %stringa% (es. %frm%)
//       ne sostituisce i valori (es. ditta corrente).
                                      
// @xref <mf TSystemisamfile::dump>
  
{
  FILE* fl = fopen(from, "r");
  int err=NOERR;
  if (fl == NULL) 
  {
    error_box("Non riesco ad aprire il file %s",from);
    return 2;
  }
  TRecnotype r = 0, e = 0, nitems = 0, nread = 0;
  TString16 firm, year, attprev("00000");

  if (extended)
  {
    TDate d(TODAY);
    TLocalisamfile ditte(LF_NDITTE);

    firm.format("%05ld", prefix().get_codditta());
    year.format("%04d", d.year());
    ditte.zero();
    ditte.put("CODDITTA", firm);
    if (ditte.read() == NOERR)
      attprev = ditte.get("CODATTPREV");
  }
  if (fl == NULL) 
  {
    clearerr(fl);
    setstatus(err);
    return err;
  }
  char w[80];
  while ((fgets(w, 80, fl) != NULL))
  {
    if (strncmp(w, "[Data]", 6) == 0)
    {
      nitems = ftell(fl);
      break;
    }
  }
  fseek(fl, 0L, SEEK_END);
  nitems = ftell(fl) - nitems;
  fclose(fl);
  TScanner f(from);

  //open();
  
  TToken_string s(1024, fs);
  bool fixedlen = (fs == '\0');
  int nflds = curr().items();
  TArray  fld(nflds);
  int    len[MaxFields];
  TString sfd(3);
  TString s1(64);
  //bool lcf = FALSE;

  if (f.paragraph("Header"))
  { 
    f.equal();
    const unsigned int level = atoi(f.line());
    const unsigned int stdlev = prefix().get_stdlevel();
    if (level > stdlev)
      error_box("L'archivio %s e' stato generato con gli archivi di livello %ld%/%ld.\n Il livello attuale e' %ld/%ld.\n Convertire gli archivi e ripetere l' operazione.", 
                from, level/100, level%100, stdlev/100, stdlev%100);
    //lcf = getlcf(level);
    nflds = 0;
    TToken_string s2(f.line());
    int p = s2.find('=');
    if (p > 0)
    {
      s1 = s2.left(p);
      s2.ltrim(p+1);
    }
    else s1.cut(0);
    while (s1 == "Fields")
    {
      for (const char * fd = s2.get(); fd != NULL;  fd = s2.get())
      {
        TToken_string wfd(fd, ',');
        fld.add(new TString(wfd.get()));
        len[nflds] = wfd.get_int();
        nflds++;
      }
      s2 = f.line();
      p = s2.find('=');
      if (p > 0)
      {
        s1 = s2.left(p);
        s2.ltrim(p+1);
      }
      else s1.cut(0);
    }
  }
  else
  {
    for (int j = 0; j < nflds; j++)
    {
      fld.add(TString(curr().fieldname(j)), j);
      const TString & wfld = (const TString & ) fld[j];
      len[j] = (curr().type(wfld) == _datefld) ? 10 : curr().length(wfld);
    }
  }
  if (!f.paragraph("Data"))
  {
    error_box("Formato dei dati non valido");
    //close();
    err = 1;
    setstatus(err);
    return err;
  }
  
  if (fd) sfd << fd;
  int last = NOERR;    
  
  s1.format("Imp. archivio %s\n%6ld records %6ld errori - %3d", filename(), r, e, last);
  TProgind p(nitems, s1, TRUE, TRUE, 70);
  s = f.line();
  while (s.not_empty() && !p.iscancelled())
  {
    if (extended)
    {
      int p, i;

      while ((p = s.find("%yr%")) >= 0)
        for (i = 0; i < 4; i++) s[p + i] = year[i];
      while ((p = s.find("%frm%")) >= 0)
        for (i = 0; i < 5; i++) s[p + i] = firm[i];
      while ((p = s.find("%att%")) >= 0)
        for (i = 0; i < 5; i++) s[p + i] = attprev[i];
    }
    if ((r + e) % 50 == 0)
    {
      s1.format("Imp. archivio %s\n%6ld records %6ld errori - %3d", filename(), r, e, last);
      p.set_text(s1);
    }
    p.setstatus(nread + 1);
    nread += s.len() + 1;
    zero();
    if (fixedlen)
    {
      int pos = 0;
      for (int j = 0; j < nflds; j++)
      {
        s1 = s.mid(pos,len[j]);
        s1.rtrim();
        put((const TString&) fld[j], s1);
        pos += len[j];
      }
    }
    else
    {
      s.restart();
      for (int j = 0; j < nflds; j++)
      {
        char* s2 = (char*) s.get();
        if (fd) 
        {
          s2++;
          s2[strlen(s2) - 1] = '\0';
        }
        put((const TString&) fld[j], s2);
      }
    }            
    if (write() == NOERR) r++;
    else 
    {
#ifdef DBG
      yesnofatal_box("Numero linea relativa all'errore: %ld",r+e+1);
#endif    
      e++;
      last = status();
    }
    s = f.line();
  }
  s1.format("Imp. archivio %s\n%6ld records %6ld errori - %3d", filename(), r, e, last);
  p.set_text(s1);
  //close();
  setstatus(err);
  return err;
}

// @mfunc Esporta VERSO un file ascii. 
//
// @rdesc Ritorna NOERR se l'operazione di esportazione e' riuscita, altrimenti il codice di
//    di errore generato (vedi <t TIsamerr>).
int TSystemtempfile::dump(
    const char* to, // @parm Nome del file verso quale esportare
    int nkey,     // @parm Numero della chiave di ordinamento con cui scaricare i dati (defualt 1)
    char fs,    // @parm Carattere seperatore di campo (defualt <pipe>)
    char fd,            // @parm Carattere delimitatore di campo (default '\\0')
    char rs,            // @parm Carattere separatore di record (default '\\n')
    bool vis,     // @parm Indica se visualizzare lo stato dell'operazione (defualt TRUE)
    bool withdeleted) // @parm Indica se scaricare anche i record cancellati (dafault FALSE)

// @xref <mf TSystemisamfile::load>

{
  FILE* f = fopen(to, "w");

  if (f == NULL) 
  {
    setstatus(2);
    return 2;
  }

  if (withdeleted) nkey = 0;
  int err = ferror(f);
  
  //open(FALSE, nkey ? TRUE : FALSE);
  TString s(512);
  bool fixedlen = (fs == '\0');
  int nflds = curr().items();
  TArray  fld(nflds);
  TBit_array rjust(nflds);
  int        len[MaxFields];

  for (int j = 0; j < nflds; j++)
  {
    fld.add(TString(curr().fieldname(j)), j);
    const TString & wfld = (const TString&) fld[j];
    const TFieldtypes t = curr().type(wfld);
    rjust.set(j, t == _intfld || t == _longfld || t == _realfld ||
              t == _wordfld || t == _intzerofld || t == _longzerofld);
    len[j] = (t == _datefld) ? 10 : curr().length(wfld);
  }
  TRecnotype i = 0;
  const TRecnotype nitems = items();
  s.format("Esportazione archivio %s", filename());
  TProgind p(nitems, s, TRUE, TRUE, 70);
  TString s1;

  fprintf(f, "[Header]\nVersion=%ld", prefix().filelevel());
  for (int k = 0; k < nflds; k++)
  {
    if ((k % 10) == 0) fprintf(f, "\nFields=");
    else fprintf(f, "|");
    fprintf(f, "%s,%d", (const char *) (const TString&) fld[k], len[k]);
  }
  fprintf(f, "\n\n[Data]\n");
  if (nkey)
  {
    setkey(nkey);
    for ( first(); status() == NOERR && !p.iscancelled(); next(), i++)
    {
      p.setstatus(i + 1);
      s = "";
      for (j = 0; j < nflds; j++)
      {
        if (fixedlen)
        {
          s1 = get((const TString&)fld[j]);
          if (rjust[j]) s1.right_just(len[j]);
          else s1.left_just(len[j]);
        }
        else
        {
          s1 = "";
          if (j && fs) s1 << fs;
          if (fd) s1 << fd;
          s1 << get((const TString&)fld[j]);
          if (fd) s1 << fd;
        }
        s << s1;
      }
      fprintf(f, "%s%c", (const char*) s, rs);
    }
  }
  else
  {

    for (i = 0; i < nitems && !p.iscancelled(); i++)
    {
      zero();
      p.setstatus(i + 1);
      readat(i + 1);
      s="";
      if (withdeleted || curr().valid())
      {
        for (j = 0; j < nflds; j++)
        {
          if (fixedlen)
          {
            s1 = get((const TString&)fld[j]);
            if (rjust[j]) s1.right_just(len[j]);
            else s1.left_just(len[j]);
          }
          else
          {
            s1 = "";
            if (j && fs) s1 << fs;
            if (fd) s1 << fd;
            s1 << get((const TString&)fld[j]);
            if (fd) s1 << fd;
          }
          s << s1;
        }
        fprintf(f, "%s%c", (const char*) s, rs);
      }
    }
  }
  p.setstatus(nitems);
  //close();
  fclose(f);
  setstatus(err);
  return err;
}

// ********************************
// classe TStd_filename
// ********************************

bool TStd_filename::check(bool verbose,const char * n)
{
  if (n && *n)
    set(n);
  insert("STD\\");
  if (!exist())
  {
    *this = name();
    if (!exist())
    {
      insert("STD\\");
      insert(prefix().get_studio());
      if (!exist())
      {
        if (verbose)
          error_box("Non riesco a trovare il file: %s", (const char *)name());
        cut(0);
        return FALSE;
      }
    }
  }
  return TRUE;
}

// ********************************
// classe TInstallmodule_app
// ********************************

bool TInstallmodule_app::create()
{
  if (modal())
  {
    TString16 maskname;
    maskname.format("bainst%02d",module_number());
    _m = new TMask(maskname);
  }
  else
    _m = NULL;

  TConfig praw(CONFIG_INSTALL, "Main");
  _test_database = praw.get("TestDatabase","Main",-1,"Y")  != "N";

  return TSkeleton_application::create();
}

bool TInstallmodule_app::destroy()
{
  if (_m) delete _m;
  return TSkeleton_application::destroy();
}

bool TInstallmodule_app::preload_mask()
{
  if (!test_database())
  {
    _m->set(F_DEFAULTSDATA," ");
    _m->disable(F_DEFAULTSDATA);
  }
  else
  {
    if (load_default_data())
      _m->set(F_DEFAULTSDATA,"X");
  }
  return TRUE;
}

bool TInstallmodule_app::some_to_load() 
{
  return _m->get_bool(F_DEFAULTSDATA);
}

void TInstallmodule_app::main_loop() 
{
  bool ok =TRUE;

  if (modal())
  {
    preload_mask();
    if (_m->run()!=K_QUIT)
    {
      if (some_to_load())
      {
        install_firm();
        install_com();
      }
    }
    else
      ok =FALSE;
  }
  if (ok)
    post_installer();
}

bool TInstallmodule_app::install_firm() 
{
  // ciclo su ogni ditta
  TStd_filename txtfile(module_code());
  txtfile << "tab.txt";
  if (txtfile.check())
  {
    TLocalisamfile ditte(LF_NDITTE);
    for (ditte.first(); !ditte.eof() ; ditte.next())
    {
      const int newditta=ditte.get_int("CODDITTA");
      if (prefix().exist(newditta))
      {
        set_firm(newditta);
        TSystemisamfile tab(LF_TAB);
          tab.load(txtfile);
      }
    }
    // carica le tabelle nei file di default
    TLocalisamfile tampone(LF_TAB);
    TSystemtempfile tabstd(LF_TAB);
    TFilename stdtabname(prefix().get_studio());
    stdtabname << "STD\\lf0005.txt";
    tabstd.load(txtfile);
    tabstd.load(stdtabname);
    tabstd.set_autodel();
    TFilename tempfile;
    tempfile.temp();
    
    // riconverte le macro delle date
    tabstd.dump(tempfile);
    TScanner scan(tempfile);
    FILE *dest=fopen((const char *)stdtabname,"w");
    while (TRUE) {
      TString &line=scan.line();
      if (line.empty()) break;

      int pos=(line.find("-0000"));
      while (pos >= 0 )
      {
        line.overwrite("%yr%",pos+1);
        pos=(line.find("-0000"));
      }
      line << '\n' ;
      fputs((const char * )line,dest);
    } 
    fclose(dest);
  }
  return TRUE;
}

bool TInstallmodule_app::install_com() 
{
  bool ok=TRUE;
  TStd_filename txtfile(module_code());
  txtfile << "tabcom.txt";
  if (txtfile.check())
  {
    TSystemisamfile tabcom(LF_TABCOM);
    tabcom.load(txtfile);
  }
  return ok;
}

void TInstallmodule_app::run(int argc, char* argv[])
{
  TScanner scanner("campo.aut");
 
  const int m = module_number();
  for (int aut = 0; aut<=m; aut++)
  {
    scanner.line();
  }
  _modcode=scanner.token().left(2);
  _modname=scanner.token().mid(3);
  
  TString title("Installazione ");
  title << module_name();
  TSkeleton_application::run(argc, argv,(const char* )title);
}


void TInstallmodule_app::set_tab_app(const char * appname)
{
  TConfig ditta(CONFIG_DITTA);
  ditta.set_paragraph(module_code());
  ditta.set("TabApp",appname);
}