#include <execp.h>
#include <tabapp.h>
#include <tabutil.h>
#include <utility.h>

// @cmember Costruttore
Tab_application::Tab_application() 
               : _msk(NULL), _rel(NULL) 
{ }

// @cmember Distruttore
Tab_application::~Tab_application() 
{ }

// @cmember Indica se la futura <mf Tab_application::get_mask> ritornera' una maschera diversa
//        dalla corrente.
bool Tab_application::changing_mask(int mode) 
{ return FALSE; }

// @cmember Richiede la maschera da usare
TMask* Tab_application::get_mask(int mode) 
{ 
  CHECK(_msk, "Null mask");
  return _msk; 
}

// @cmember Ritorna la relazione da modificare
TRelation* Tab_application::get_relation() const 
{ 
  CHECK(_rel, "Null relation");
  return _rel; 
}

void Tab_application::print()
{
  TString16 cmd;
  cmd << "ba3 -1 " << get_tabname();
  TExternal_app stampa(cmd);
  stampa.run();
}

void Tab_application::init_query_mode(TMask& m) 
{
  m.enable(-GR_MODIFY_PROTECTED);
  m.enable(-GR_RECORD_PROTECTED);
}

void Tab_application::init_modify_mode(TMask& m) 
{
  m.disable(-GR_MODIFY_PROTECTED);
  const bool enable = !(_rel->curr().get_bool(FPC));
  m.enable(-GR_RECORD_PROTECTED,enable);
}

bool Tab_application::protected_record(TRectype& rec) 
{ 
  return rec.get_bool(FPC);
}

TString Tab_application::mask_name()
{
  TString16 t(_tabname);
  
  if (t[0] == '%') t.ltrim(1);
  TString16 m; m << "batb" << t;
  return m.upper();

}

  

TMask * Tab_application::set_mask(TMask * _m)
{
	if (_m!=NULL) 
	{
		// imposta la maschera come maschera della applicazione
		if (_msk!=NULL)  
			delete _msk;
		_msk=_m;
	} else {
		// alloca la maschera standard come maschera della applicazione
		_msk = new TMask((const char *)mask_name()) ;
	}
 	return _msk;
}

bool Tab_application::user_create()
{
  if (argc() < 3) 
    return FALSE;
  
  _tabname = argv(2);
  _tabname.upper();
  _rel = new TRelation(_tabname);
  
  
  set_mask();
  
  const int campi = _msk->fields();
  for (int i = 0; i < campi; i++)
  {
    const TMask_field& f = _msk->fld(i);
    if (f.in_group(GR_SEARCH))
    {
      set_search_field(f.dlg());
      break;
    }
  }
  
  TFilename rpt(mask_name()); rpt << ".rpt";
  if (fexist(rpt)) 
    enable_menu_item(M_FILE_PRINT);
  
  const char* title = _msk->get_caption();
  set_title(title);
  return TRUE;
}

bool Tab_application::user_destroy() 
{
  if (_msk) delete _msk;
  if (_rel) delete _rel;

  return TRUE;
}

