#include "baformed.h"
#include "ba2100.h"


class TForm_EC_editor : public TForm_editor
{
  TMask* _msk;    
protected:
  virtual bool create();
  virtual bool destroy();
public:
  TForm_EC_editor();
  virtual ~TForm_EC_editor();  
};           


TForm_EC_editor::TForm_EC_editor()
{}

TForm_EC_editor::~TForm_EC_editor()
{}

bool TForm_EC_editor::create()
{             
  TApplication::create();

  const char* form = NULL;
  const char* code = NULL;
  
  for (int a = 2; a < argc(); a++)
  {
    if (stricmp(argv(a), "-E") == 0)
    {
      extra() = TRUE;
      continue;
    }  
    
    if (form == NULL)
      form = argv(a);
    else                  
      if (code == 0)
        code = argv(a);
  }

  bool go = FALSE;
  
  if ((form && code) || (form && code == NULL && extra()))
  {
    set_form(new TForm(form, code, extra() ? 2 : 1));
    enable_menu_item(M_FILE_PRINT);
    if (!extra()) dispatch_e_menu(MENU_ITEM(31));
  } 
  else
  {  
    _msk = new TMask("ba2500a");

    if (form)
    {
      _msk->set(F_BASE, form);
      _msk->disable(F_BASE);
    }
    
    TString16 s(code);
    if (code) 
    {
      _msk->set(F_CODEPR, s.mid(0,4));
      _msk->set(F_CODEL, s.mid(4,1));
    }

    // choose form from mask 
    KEY k; 
    while ((k = _msk->run()) != K_QUIT)
    {
      TString16 fform = _msk->get(F_BASE);
      TString80 fdesc = _msk->get(F_DESCPR);
      TString16 fcode = _msk->get(F_CODEPR); 
      fcode << _msk->get(F_CODEL);
      
      if (k == K_ENTER)
      {
        set_form(new TForm(fform, fcode, extra() ? 2 :1, fdesc));    
        form = fform;
        go  = TRUE;
        break;
      }            
      else if (k == K_DEL)
      {
        if (yesno_box("Confermare la cancellazione del profilo %s", (const char*)fcode))
        { 
          TLocalisamfile frm(LF_FORM);
          frm.zero(); 
          frm.put("TIPOPROF", fform);
          frm.put("CODPROF",  fcode);
          if (frm.read() == NOERR)
            frm.remove();
          TLocalisamfile rfr(LF_RFORM);
          rfr.zero(); 
          rfr.put("TIPOPROF", fform);
          rfr.put("CODPROF",  fcode);
          if (rfr.read() == NOERR)
          {
            for ( ; rfr.get("CODPROF") == fcode && rfr.get("TIPOPROF") == fform; rfr.next())
              rfr.remove();
          }
          _msk->set(F_CODEPR,"");
          _msk->set(F_CODEL,"");
          _msk->set(F_BASE,"");
          _msk->set(F_DESCPR,"");
        }
      }
    }
  }
  if (go)
  {
    enable_menu_item(M_FILE_PRINT);
    if (!extra()) dispatch_e_menu(MENU_ITEM(31));       
  }
  
  return form != NULL;
}

bool TForm_EC_editor::destroy()
{           
  if (_msk)
    delete _msk;
  return TForm_editor::destroy();
}

int ba2500(int argc, char* argv[])
{                                             
  TForm_EC_editor a;      
  a.run(argc, argv, "Gestione profili EC");
  return 0;
}
