#include <config.h>
#include <execp.h>
#include <modaut.h>
#include <recarray.h>
#include <tabutil.h>

#include "bainstlib.h"
#include "bainst.h"
#include "bainst00.h"

class TInstall_BA : public TInstallmodule_app
{
private:
  
protected:
  virtual int module_number() const { return 0; }
  virtual bool install_com();
  virtual bool post_installer();
  virtual bool preload_mask();
	virtual bool something_to_load() const;
  virtual bool something_checked() const;

public:
  virtual ~TInstall_BA () {}
};

HIDDEN int search_edit(TConfig& cfg, void*)
{ 
  const TString16 module = cfg.get_paragraph().left(2); 
  TAssoc_array& var = cfg.list_variables(); 
  bool dirty = FALSE;
  FOR_EACH_ASSOC_STRING (var, obj, key, str)
  {
    const TFixed_string confr (key);
    if (confr.compare("Edit_", 5, TRUE) == 0)
    {
      if (module.compare(str, 2, TRUE) != 0)
      {
        cfg.remove(key);
        dirty = TRUE;
      }
    }
  }
  if (dirty)
  {
    cfg.set_paragraph("");
  }
  return FALSE;
}

bool TInstall_BA::post_installer()
{
  // configurazione provvisoria dei programmi gestori di tabelle
  if (!test_database())
  {
    TConfig studio(CONFIG_STUDIO);
    const char *confapp="EdApp";
    const char *tabapp="TabPrg";
    // magazzino  
    studio.set_paragraph("mg");
    studio.set(tabapp,"mg0 -0");
    studio.set(confapp,"mg0 -2 -1");
    // distinta base
    studio.set_paragraph("db");
    studio.set(tabapp,"db0 -0");
    studio.set(confapp,"");
    // statistiche
    studio.set_paragraph("sv");
    studio.set(tabapp,"sv0 -0");
    studio.set(confapp,"sv0 -3");
    // provvigioni
    studio.set_paragraph("pr");
    studio.set(tabapp,"pr0 -4");
    // MRP
    studio.set_paragraph("mr");
    studio.set(tabapp,"mr0 -0");
  }
  
  TConfig install ("install.ini");
  install.for_each_paragraph(search_edit, NULL);

  return true;
}
 
bool TInstall_BA::something_checked() const 
{
  return _m->get_bool(F_DATI_IVA) || TInstallmodule_app::something_checked();
}

bool TInstall_BA::something_to_load() const
{
	if (test_database())
	{
		TTable iva("%IVA");
		if (iva.empty())
			return true;
	}
	return TInstallmodule_app::something_to_load();
}

bool TInstall_BA::preload_mask()
{
  if (has_module(CGAUT) || has_module(VEAUT))
  {
	  if (something_to_load())
		  _m->set(F_DATI_IVA, "X");
  }
  else
    _m->hide(F_DATI_IVA);

	return TInstallmodule_app::preload_mask();
}

bool TInstall_BA::install_com() 
{
	//i codici iva vanno a parte
  TStd_filename txtfile;
  if (_m->get_bool(F_DATI_IVA) && txtfile.check(TRUE,"lfiva.txt"))
  {
    TSystemisamfile tabcom(LF_TABCOM);
    tabcom.load(txtfile);
  }

  return TInstallmodule_app::install_com();
}

int bainst00(int argc, char** argv)
{ 
  TInstall_BA app;
  app.run(argc, argv);
  return 0;
}