#include <relapp.h>
#include <stdtypes.h>
#include <utility.h>

#include "ba4.h"
#include "ba4600.h"

class TSoci_application : public TRelation_application
{
  TMask* _msk;
  TRelation* _rel;
  TLocalisamfile* _anag;
  TLocalisamfile* _ditte;

  bool user_create() ;                         
  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;}

public:
  TSoci_application() {}
  virtual ~TSoci_application() {}
  virtual void init_query_mode(TMask& m) ;
  virtual void init_query_insert_mode(TMask& m) ;
  virtual int rewrite(const TMask& m);
  virtual int write(const TMask& m);
  virtual void update_ap_socio(const TMask& m);
};

void TSoci_application::init_query_mode(TMask& m)

{
  m.show(FLD_SC1_CODANAGRSOH);
  m.hide(FLD_SC1_CODANAGRSO);
  m.set(FLD_SC1_CODANAGR_ANAGR_RAGSOC, "");
}


void TSoci_application::init_query_insert_mode(TMask& m)

{
  m.show(FLD_SC1_CODANAGRSO);
  m.hide(FLD_SC1_CODANAGRSOH);
  m.set(FLD_SC1_CODANAGR_ANAGR_RAGSOC, "");
}

void TSoci_application::update_ap_socio(const TMask& m)
{
  int err = NOERR;
  const char ap = (m.get(FLD_SC1_ANNO)[0] == 'A') ? 'P' : 'A';

  if (yesno_box(format("Aggiornare anche il socio %s?", ap == 'A' ? "attuale" : "precedente")))
  {
    _rel->save_status();
    m.autosave(_rel);
    _rel->lfile().put("ATTPREC", ap);
    const bool was =_rel->read(_isequal, _lock) == NOERR;
    m.autosave(_rel);
    _rel->lfile().put("ATTPREC", ap);
    if (was) err = _rel->rewrite();
    else err = _rel->write();
    if (err != NOERR)
      error_box("Aggiornamento socio %s - Errore : %d", ap == 'A' ? "attuale" : "precedente", err); 
    _rel->restore_status();
  }
}

int TSoci_application::write(const TMask& m)
{
  const int err = TRelation_application::write(m);
  if (err == NOERR)
    update_ap_socio(m);
  return err;
}

int TSoci_application::rewrite(const TMask& m)
{
  const int err = TRelation_application::rewrite(m);
  if (err == NOERR)
    update_ap_socio(m);
  return err;
}

bool TSoci_application::user_create() 
{
  _rel = new TRelation(LF_SOCI) ;
  _anag = new TLocalisamfile(LF_ANAG) ;
  _ditte = new TLocalisamfile(LF_NDITTE) ;
  _msk = new TMask("ba4600a") ;
  set_search_field(FLD_SC1_CODANAGRSOH);
  return TRUE;
}

bool TSoci_application::user_destroy() 
{
  delete _msk;
  delete _ditte;
  delete _anag;
  delete _rel;
  return TRUE;
}

int ba4600(int argc, char* argv[])
{
  TSoci_application a ;
  a.run(argc, argv, "Anagrafica Soci");
  return 0;
}
