#include <applicat.h>
#include <date.h>
#include <modaut.h>
#include <mask.h>
#include <prefix.h>
#include <utility.h>
#include <urldefid.h>

#include <extcdecl.h>

#include "ba1.h"
#include "ba0100a.h"
#include "ba1500a.h"

#define USERADR    26952
#define AGAADR     26953
#define PRASSIADR  26954
#define K1         0x4500
#define LBYTEMASK   0x00FF
#define UBYTEMASK  0xFF00
#define MAXAUT     49

enum KeyType { _user_key, _aga_key, _prassi_key};

#define  BITTEST(w,p) (((w) & (0x0001 << (p))) != 0)
#define  BITSET(w,p,v)  ((v) ? ((w) |= (0x0001 << (p))) : ((w) &= (~(0x0001 << (p)))))

class TAttivazione_moduli : public TApplication
{
  TMask* _msk;

  KeyType _key_type;
  word _serno;
  word _port;

  virtual bool create() ;                         
  virtual bool destroy() ;                        
  virtual bool use_files() const { return FALSE; }
  virtual bool menu(MENU_TAG);
  
  void generate_key();
  static void keyext(const TString & s, word * v);
  static bool user_hnd(TMask_field & f, KEY k);
  static bool decode_hnd(TMask_field & f, KEY k);
  static bool activate_hnd(TMask_field & f, KEY k);

public:
  TAttivazione_moduli() : _msk(NULL) { _key_type = _user_key;}
};


HIDDEN TAttivazione_moduli& app() { return (TAttivazione_moduli &)main_app(); }


void TAttivazione_moduli::generate_key()
{
#if XVT_OS == XVT_OS_SCOUNIX
  word ud[4];
  INT_OFF();
  HL_ON(_port, USERADR);
  ud[0] = HL_RD(_port, 48);
  ud[1] = HL_RD(_port, 49);
  ud[2] = HL_RD(_port, 50);
  ud[3] = HL_RD(_port, 51);
  HL_OFF(_port);
  INT_ON();
#else
  int ud[4];
  HL_READ(48, &ud[0]);
  HL_READ(49, &ud[1]);
  HL_READ(50, &ud[2]);
  HL_READ(51, &ud[3]);
#endif
  
  int    nmod = 0;

  _msk->set(F_K2, format("%04X%04X%04X%04X", ud[0], ud[1], ud[2], ud[3]));
  for (int i = 1; i < MAXAUT; i++)
  {
    const int pos = _msk->id2pos(F_BASE + i);

    if (pos >= 0 && has_module(i, CHK_DONGLE))
    {
      _msk->fld(pos).set("X");
      nmod++;
    }
  }

  _serno = SerNo;
  ud[0] = _serno;
  ud[1] = K1 | (nmod & LBYTEMASK);
  long & l = (long &) ud[2];
  TDate d(TODAY);

  l = d.year()*10000L + d.month()*100L + d.day();
#if XVT_OS == XVT_OS_SCOUNIX
  INT_OFF();
  HL_ON(_port, ModAd);
  K_EYE(_port, (unsigned char *) ud, HLBLOCK);
  HL_OFF(_port);
  INT_ON();
#else
  HL_CODE(EYECAST &ud[0], HLBLOCK);
#endif
  _msk->set(F_K1, format("%04X%04X%04X%04X", ud[0], ud[1], ud[2], ud[3]));
  _msk->set(F_SN, SerNo);
  _msk->set(F_DT, d.string());
}

int hexdigit(char c)
{
  static char s[] = "0123456789ABCDEF";
  int i = strlen(s);

  while (i-- >= 0)
    if (s[i] == c)
      break;
  return i;
}

void TAttivazione_moduli::keyext(const TString& s, word * val)
{
  for (int i = 0 ; i < 4; i++)
  {
    const int off = i * 4;
    word & l = val[i];
    
    l = 0;
    for (int j = 0; j < 4; j++)
      l = l * 16 + hexdigit(s[off + j]);
  }
}

bool TAttivazione_moduli::user_hnd(TMask_field & f, KEY k)
{
  const TString16 k4(f.get());
  if (!f.to_check(k) || k4.empty()) return TRUE;
  TMask & m = f.mask();
  word     ud1[4], ud2[4], port = app()._port;
  const TString16 k3(m.get(F_K3));
  
  keyext(k3, ud1);
  keyext(k4, ud2);
#if XVT_OS == XVT_OS_SCOUNIX
  INT_OFF();
  HL_ON(port, ModAd);
  K_EYE(port, (unsigned char *) ud1, HLBLOCK);
  HL_OFF(port);
  INT_ON();
#else
  HL_CODE(EYECAST ud1, HLBLOCK);
#endif
  const long & l = (long &) ud1[0];
  TDate d(l), d1(TODAY);

  d.addmonth(3);
  if (d < d1)
    return f.error_box("data non valida");
  if ((ud1[2] & UBYTEMASK) != K1 || ud1[3] != app()._serno) 
    return f.error_box("primo codice errato");
#if XVT_OS == XVT_OS_SCOUNIX
  INT_OFF();
  HL_ON(port, ModAd);
  K_EYE(port, (unsigned char *) ud2, HLBLOCK);
  HL_OFF(port);
  INT_ON();
#else
  HL_CODE(EYECAST ud2, HLBLOCK);
#endif
  for (int i = 0; i < 4; i++) ud2[i] ^= app()._serno;
  if (ud2[3] != 0) 
    return f.error_box("secondo codice errato");
  for (i = 1; i < MAXAUT; i++)
  {
    const int af = i - 1;
    const int pos = m.id2pos(F_BASE + i);

    if (pos >= 0)
      m.fld(pos).set(BITTEST(ud2[af / 16], af % 16) ? "X" : " ");
  }
  if (k == K_ENTER)
  {
    keyext(k4, ud2);
#if XVT_OS == XVT_OS_SCOUNIX
    INT_OFF();
    HL_ON(port, ModAd);
    HL_ON(port, ModAd);
    HL_WR(port, 48, ud2[0]);
    HL_WR(port, 49, ud2[1]);
    HL_WR(port, 50, ud2[2]);
    HL_WR(port, 51, ud2[3]);
    HL_OFF(port);
    INT_ON();
#else
    HL_WRITE(48, ud2[0]);
    HL_WRITE(49, ud2[1]);
    HL_WRITE(50, ud2[2]);
    HL_WRITE(51, ud2[3]);
#endif
  }
  return TRUE;
}

bool TAttivazione_moduli::decode_hnd(TMask_field & f, KEY k)
{
  const TString16 k2(f.get());
  if (!f.to_check(k) || k2.empty()) return TRUE;
  TMask & m = f.mask();
  word     ud1[4], ud2[4], port = app()._port;
  const TString16 k1(m.get(F_K1));
  
  keyext(k1, ud1);
  keyext(k2, ud2);
#if XVT_OS == XVT_OS_SCOUNIX
  INT_OFF();
  HL_ON(port, USERADR);
  K_EYE(port, (unsigned char *) ud1, HLBLOCK);
  HL_OFF(port);
  INT_ON();
#else
  HL_CODE(EYECAST ud1, HLBLOCK);
#endif
  long & l = (long &) ud1[2];
  const TDate  d(l);
  app()._serno = ud1[0];
  if ((ud1[1] & UBYTEMASK) != K1)
    return f.error_box("primo codice errato");
#if XVT_OS == XVT_OS_SCOUNIX
  INT_OFF();
  HL_ON(port, USERADR);
  K_EYE(port, (unsigned char *) ud2, HLBLOCK);
  HL_OFF(port);
  INT_ON();
#else
  HL_CODE(EYECAST ud2, HLBLOCK);
#endif
  for (int i = 0; i < 4; i++) ud2[i] ^= app()._serno;
  if (ud2[3] != 0)
    return f.error_box("secondo codice errato");
  m.set(F_SN, app()._serno);
  m.set(F_DT, d.string());
  for (i = 1; i < MAXAUT; i++)
  {
    const int af = i - 1;
    const int pos = m.id2pos(F_BASE + i);

    if (pos >= 0)
      m.fld(pos).set(BITTEST(ud2[af / 16], af % 16) ? "X" : " ");
  }
  return TRUE;
}

bool TAttivazione_moduli::activate_hnd(TMask_field & f, KEY k)
{
  TMask & m = f.mask();
  word    ud1[4], ud2[4], port = app()._port;
  int     nmod = 0;
  
  for (int i = 0; i < 4; i++) ud2[i] = 0;
  for (i = 1; i < MAXAUT; i++)
  {
    const int af = i - 1;
    const int pos = m.id2pos(F_BASE + i);

    if (pos >= 0 && m.get_bool(F_BASE + i))
    {
      BITSET(ud2[af / 16], af % 16, TRUE);
      nmod++;
    }
  }
  for (i = 0; i < 4; i++) ud2[i] ^= app()._serno;

  const TDate d(m.get(F_DT));
  long & l = (long &) ud1[0];
  
  l = d.year()*10000L + d.month()*100L + d.day();
  ud1[2] = K1 | (nmod & UBYTEMASK);
  ud1[3] = app()._serno;
#if XVT_OS == XVT_OS_SCOUNIX
  INT_OFF();
  HL_ON(port, ModAd);
  K_EYE(port, (unsigned char *) ud1, HLBLOCK);
  K_EYE(port, (unsigned char *) ud2, HLBLOCK);
  HL_OFF(port);
  INT_ON();
#else
  HL_CODE(EYECAST ud1, HLBLOCK);
  HL_CODE(EYECAST ud2, HLBLOCK);
#endif
  m.set(F_K4, format("%04X%04X%04X%04X", ud2[0], ud2[1], ud2[2], ud2[3]));
  m.set(F_K3, format("%04X%04X%04X%04X", ud1[0], ud1[1], ud1[2], ud1[3]));
  return TRUE;
}

bool TAttivazione_moduli::create()
{
  if (user() != "PRASSI") 
    return error_box("Utente non abilitato all'uso di questo programma");
  
  disable_menu_item(M_FILE_NEW);
  disable_menu_item(M_FILE_REVERT);
  disable_menu_item(M_FILE_PG_SETUP);

  _msk = new TMask("ba1500a") ;
#if XVT_OS == XVT_OS_SCOUNIX
  if (Hl_Port(AGAADR) != 0)
    _key_type = _aga_key;
  else
    if (Hl_Port(PRASSIADR) != 0)
      _key_type = _prassi_key;
  _port = Hl_Port(USERADR);
#else
  HL_LOGOUT();
  if (HL_LOGIN(AGAADR, DONT_CARE, REFKEY, VERKEY) == STATUS_OK) 
    _key_type = _aga_key;
  else
  {
    HL_LOGOUT();
    if (HL_LOGIN(PRASSIADR, DONT_CARE, REFKEY, VERKEY) == STATUS_OK)
      _key_type = _prassi_key;
  }
  HL_LOGOUT();
  HL_LOGIN(USERADR, DONT_CARE, REFKEY, VERKEY);
#endif

  switch (_key_type)
  {
  case _user_key:
  {
    _msk->disable(F_K1);
    _msk->disable(F_K2);
    _msk->set_handler(F_K4, user_hnd);
    generate_key();
    for (int i = 1; i < ENDAUT; i++)
    {
      const int pos = _msk->id2pos(F_BASE + i);
      if (pos >= 0) _msk->fld(pos).disable();
    }
  }
  break;
 case _aga_key:
 case _prassi_key:
{
  _msk->set_handler(F_K2, decode_hnd);
  _msk->disable(F_K3);
  _msk->disable(F_K4);
  for (int i = 1; i < MAXAUT; i++)
  {
    const int pos = _msk->id2pos(F_BASE + i);
    
    if (pos >= 0)
      _msk->set_handler(F_BASE + i, activate_hnd);
  }
}
break;
default:
break;
}
dispatch_e_menu(BAR_ITEM(1));
return TRUE;
}

bool TAttivazione_moduli::destroy()
{
  if (_msk != NULL) delete _msk;
  return TRUE;
}

bool TAttivazione_moduli::menu(MENU_TAG)
{
  _msk->run();
  return FALSE;
}

int ba1500(int argc, char** argv)
{
  TAttivazione_moduli a ;
  a.run(argc, argv, "Attivazione moduli");
  return 0;
}
