#include <stdio.h>

#include <relapp.h>
#include <stdtypes.h>
#include <modaut.h>
#include <prefix.h>
#include <utility.h>
#include <msksheet.h>

#include "ba1.h"
#include "ba1500.h"
#include "ba0100a.h"

class TSet_users : public TRelation_application
{
  TMask* _msk;
  TRelation* _rel;
  TInformazione_moduli* _im;

  virtual bool user_create();                         
  virtual bool user_destroy();                        
  virtual TMask* get_mask(int mode) { return _msk;}
  virtual bool changing_mask(int mode) { return FALSE;}
  virtual TRelation* get_relation() const { return _rel;}
  virtual int read(TMask& m);
  void        put_in_record(const TMask& m);
  virtual int write(const TMask& m); 
  virtual int rewrite(const TMask& m);
  virtual bool remove();
  
  void   enable_aut(TMask& m);
  static bool user_handler(TMask_field& f, KEY key);
  static bool password_handler(TMask_field& f, KEY key);
  static bool k_notify(TSheet_field & f, int r, KEY k);
  virtual void  init_query_mode(TMask& m) { enable_aut(m);}
  virtual void  init_insert_mode(TMask& m) { build_sheet(m,NULL); enable_aut(m);}
  virtual void  init_modify_mode(TMask& m) { enable_aut(m);}
  TSheet_field& sheet_field() { return (TSheet_field&) _msk->field(F_MODULI);}
  void          build_sheet(TMask& m, const TRelation* r);

public:
  TSet_users() : _msk(NULL), _rel(NULL) {}
};

bool TSet_users::user_handler(TMask_field& f, KEY key)

{
  if (!f.mask().query_mode() || !f.to_check(key)) return TRUE;
  
  const bool ok = f.get().find(' ') < 0;

  if (!ok) return f.error_box("Il nome dell'utente non deve contenere spazi");
  return ok;
}

bool TSet_users::password_handler(TMask_field& f, KEY key)

{
  if (f.mask().query_mode() || key != K_ENTER) return TRUE;
  const bool ok = f.get().len() > 3 && f.get().find(' ') < 0;

  if (!ok) return f.error_box("La password deve essere lunga almeno 4 caratteri e non contenere spazi");
  return ok;
}

void TSet_users::build_sheet(TMask& m, const TRelation* r)
{
  TString autstr;
  TSheet_field& sf = sheet_field();
  if (r != NULL)
    autstr = r->lfile().get("AUTSTR");
  const int l = autstr.len();
  sf.destroy();
  
  for (int i = 0; i < ENDAUT; i++)
  {
    TString d( _im->get_description_by_order(i));
    if (d.trim().empty()) continue;
    TToken_string& riga = sf.row(i);
    riga = d;
    const int module = _im->get_module_by_order(i);
    if (r!= NULL && module<l && autstr[module]=='X')
      riga.add("X");
    else riga.add(" ");
    riga.add(module);
  }


}

void TSet_users::enable_aut(TMask& m)
{
  const bool prassi = (m.get(F_USER) == "PRASSI");
  const int uns = _im->unassigned();
  TSheet_field& sf = sheet_field();
  const int itms = sf.items();
  for (int i = 0; i < itms; i++)
  {
    const int module = _im->get_module_by_order(i+uns);
    TToken_string& riga = sf.row(i);
    if (module == BAAUT || module == MUAUT)
    {
      sf.disable_cell(i,1);
      riga.add("X",1);
    }
    else
    {
      sf.enable_cell(i,1,!prassi && has_module(module, CHK_DONGLE));
      if (prassi) riga.add("X",1);
    }
  }
}

bool TSet_users::k_notify(TSheet_field& f, int r, KEY k)
{
  if (k == K_INS)
    return FALSE;
  return TRUE;
}

bool TSet_users::user_create()
{
  if (user() != "PRASSI") 
    return error_box("Utente non abilitato all'uso di questo programma");
  _msk = new TMask("ba1400a") ;
  _rel = new TRelation(LF_USER);
  _msk->set_handler(F_USER, user_handler);
  _msk->set_handler(F_PASSWORD, password_handler);
  TSheet_field& sf = sheet_field();
  sf.set_notify(k_notify);
  _im = new TInformazione_moduli;
  
  return TRUE;
}

int TSet_users::read(TMask& m) 

{
  TRelation_application::read(m);
  const TRelation *r = get_relation();
  build_sheet(m,r);
  m.set(F_PASSWORD, decode(r->lfile().get("PASSWORD")));
  return NOERR;
}


void TSet_users::put_in_record(const TMask& m) 
{
  TRelation *r = get_relation();
  TString16 s(encode(m.get(F_PASSWORD)));
  TString   autstr(ENDAUT);
  TSheet_field& sf = sheet_field();
  const int itms = sf.items();
  
  autstr.fill(' ');
  for (int i=0; i<itms; i++)
  {
    TToken_string& riga = sf.row(i);
    const int module = atoi(riga.get(2));
    const char c = riga.get(1)[0];
    if ( c == 'X')
      autstr[module] = c;
  }
  
  r->lfile().put("AUTSTR", (const char *) autstr);
  r->lfile().put("PASSWORD", (const char *) s);
}  

int TSet_users::write(const TMask& m) 
{
  put_in_record(m);
  return TRelation_application::write(m);
}

int TSet_users::rewrite(const TMask& m) 
{
  put_in_record(m);
  return TRelation_application::rewrite(m);
}

bool TSet_users::remove()
{
  const bool ok = TRelation_application::remove();
  if (ok)
  {
    const TString16 u = get_relation()->curr().get("USERNAME");
    TFilename file = firm2dir(-1);       // Directory dati
    file.add("config");                  // Directory configurazioni
    file.add(u);                         // Nome utente
    file.ext("ini");                     // Estensione
    ::remove(file);
  }
  return ok;
}

bool TSet_users::user_destroy()
{
  if (_msk != NULL) delete  _msk;
  if (_rel != NULL) delete  _rel;
  if (_im != NULL)  delete  _im;
  return TRUE;
}

int ba1400(int argc, char** argv)
{
  TSet_users a ;
  a.run(argc, argv, "Configurazione utenti");
  return 0;
}
