#include <applicat.h>
#include <mask.h>
#include <form.h>
#include <utility.h>
#include <urldefid.h>

class TEdit_form : public TApplication
{
  const char* _name;
  TMaskmode _mode;
  TForm* _form;

protected:
  virtual bool create();
  virtual bool destroy();
  virtual bool menu(MENU_TAG);

public:
  TEdit_form(const char* name, TMaskmode mode);
  const char* name() const { return _name; }
};


TEdit_form::TEdit_form(const char* name, TMaskmode mode)
: _name(name), _mode(mode), _form(NULL)
{}


bool TEdit_form::create()
{
  _form = new TForm(name());
  dispatch_e_menu(MENU_ITEM(2));
  return TRUE;
}


bool TEdit_form::destroy()
{
  delete _form;
  return TRUE;
}


bool TEdit_form::menu(MENU_TAG tag)
{
  int sec = 1;
  switch(tag)
  {
  case MENU_ITEM(1): sec = 0; break;
                   case MENU_ITEM(3): sec = 2; break;
                     default          : sec = 1; break;
                   }
  _form->edit(_mode, sec);
  return TRUE;
}


int cg1300(int argc, char* argv[])
{
  int arg = argc;
  if (strncmp(argv[arg - 1], "-u", 2) == 0) arg--;
  if (arg < 3)
  {
    error_box("Specificare il nome del profilo di stampa");
    return 1;
  }

  TFilename form(argv[2]); form.ext("frm");

  const char mode = arg > 3 ? toupper(argv[3][1]) : ' ';

  const bool crea = (mode == 'C') || !fexist(form);
  if (crea)
  {
    TFilename base(form.left(3)); base.ext("frm");
    if (!fexist(base))
    {
      error_box("Non esiste il file %s", (const char*)base);
      return 1;
    }
    if (!fcopy(base, form))
    {
      error_box("Impossibile copiare %s in %s", (const char*)base, (const char*)form);
      return 1;
    }
  }

  if (!fexist(form))
  {
    error_box("Non esiste il file %s", (const char*)form);
    return 1;
  }

  TEdit_form a(form, (mode == 'I') ? MODE_INS : MODE_MOD);
  TString title(40);
  title << "Modifica modello: " << a.name();
  a.run(argc, argv, title);

  return 0;
}
