#include <stdlib.h>

#include <xvt.h>

#if XVT_OS == XVT_OS_WIN
#define STRICT
#include <windows.h>
#include <toolhelp.h>
#endif

#include <extcdecl.h>
#include <modaut.h>

#include <applicat.h>
#include <colors.h>
#include <config.h>
#include <mask.h>
#include <prefix.h>
#include <printer.h>
#include <progind.h>
#include <relation.h>
#include <urldefid.h>
#include <utility.h>

#include <bagn002.h>

#define  BITTEST(w,p) (((w) & (0x0001 << (p))) != 0)


///////////////////////////////////////////////////////////
// Metodi di accesso globali all'applicazione corrente
///////////////////////////////////////////////////////////

HIDDEN TApplication* _application = NULL;

TApplication& main_app()
{
  CHECK(_application, "NULL application!");
  return *_application;
}

bool xvt_running() { return _application != NULL; }

///////////////////////////////////////////////////////////
// Gestione dello sfondo della finestra principale
///////////////////////////////////////////////////////////

HIDDEN long backdrop_eh( WINDOW  win, EVENT* ep)
{
  xvt_dwin_clear(win, MASK_DARK_COLOR);
  return 0L;
}

HIDDEN void create_backdrop( void )
{
#if XVT_OS == XVT_OS_WIN
  xvt_create_statbar();
  xvt_statbar_set("");
#else
  xvt_app_escape(XVT_ESC_CH_COLOR, XVT_CH_CLR_MENU,     COLOR_BLACK, COLOR_WHITE);
  xvt_app_escape(XVT_ESC_CH_COLOR, XVT_CH_CLR_DIALOG,   COLOR_BLUE,  COLOR_WHITE);
  xvt_app_escape(XVT_ESC_CH_COLOR, XVT_CH_CLR_WINDOW,   COLOR_RED,   COLOR_WHITE);
  xvt_app_escape(XVT_ESC_CH_COLOR, XVT_CH_CLR_CONTROL,  COLOR_BLACK, COLOR_WHITE);
  xvt_app_escape(XVT_ESC_CH_COLOR, XVT_CH_CLR_DISABLED, COLOR_GRAY,  COLOR_WHITE);
  xvt_app_escape(XVT_ESC_CH_COLOR, XVT_CH_CLR_MNEMONIC, COLOR_RED,   COLOR_WHITE);

  RCT rct;
  xvt_vobj_get_client_rect( TASK_WIN, &rct );
  xvt_win_create(W_PLAIN, &rct, (char*) 0, 0, TASK_WIN,
                 WSF_NO_MENUBAR | WSF_CH_BACKDROP , EM_UPDATE,
                 backdrop_eh, 0L );
#endif
}

///////////////////////////////////////////////////////////
// Gestione del banner iniziale
///////////////////////////////////////////////////////////

class TBanner : public TWindow
{ 
protected:
  virtual void handler(WINDOW win, EVENT* ep);

public:
  TBanner();
  virtual ~TBanner();
};

TBanner::TBanner()
{
  create(-1, 6, 72, 6, "BANNER", WSF_NONE, W_PLAIN);
  hide_brush();
  open();
  do_events();
}

TBanner::~TBanner()
{      
  if (is_open())
    close();
}

void TBanner::handler(WINDOW win, EVENT* ep)
{
  if (ep->type == E_UPDATE)
  { 
    const int BIGY = 3*CHARY/2;
    
    clear(COLOR_LTGRAY);
    RCT r; xvt_vobj_get_client_rect(win, &r);

    set_color(COLOR_WHITE, COLOR_LTGRAY);
    set_font(XVT_FFN_TIMES, XVT_FS_BOLD | XVT_FS_ITALIC, BIGY);
    char* t = (char*)(const char*)main_app().title();
    int w = xvt_dwin_get_text_width(win, t, -1);
    int a; xvt_dwin_get_font_metrics(win, NULL, &a, NULL);
    int x = (r.right-w)>>1, y = (r.bottom+a)>>1 ;
    xvt_dwin_draw_text(win, x+1, y+1, t, -1);
    set_color(COLOR_BLACK, COLOR_LTGRAY);
    xvt_dwin_draw_text(win, x, y, t, -1);

    set_font(XVT_FFN_TIMES);
    t = "PRASSI S.p.A.";
    w = xvt_dwin_get_text_width(win, t, -1);
    x = (r.right-r.left-w)>>1, y = BIGY;
    xvt_dwin_draw_text(win, x, y, t, -1);

    t = "Caricamento in corso";
    w = xvt_dwin_get_text_width(win, t, -1);
    x = (r.right-r.left-w)>>1, y = r.bottom - CHARY;
    xvt_dwin_draw_text(win, x, y, t, -1);

    r.left += 5; r.right -= 4;
    r.top += 5; r.bottom -= 4;
    set_pen(COLOR_WHITE); xvt_dwin_draw_rect(win, &r);
    xvt_rect_offset(&r, -1, -1);
    set_pen(COLOR_BLACK); xvt_dwin_draw_rect(win, &r);
    
    xvt_dwin_draw_icon(win, CHARX<<1, CHARX<<1, ICON_RSRC); 
  }
  else
    TWindow::handler(win, ep);
}

long XVT_CALLCONV1 TApplication::task_eh(WINDOW win, EVENT *ep)
{
  switch (ep->type)
  {
  case E_CREATE:
    create_backdrop();
#if defined(DBG) && XVT_OS == XVT_OS_SCOUNIX
    message_box("Attach to process %d ...", getpid());
#endif
    do_events();
    break;
#if XVT_OS == XVT_OS_WIN
  case E_UPDATE:
    backdrop_eh(win, ep);
    break;
#endif
  default:
    break;
  }

  return _application->handler(win, ep);
}

long TApplication::handler(WINDOW win, EVENT* ep)
{
  switch (ep->type)
  {
  case E_CREATE:
  {
    TBanner banner;
    _create_ok = create();
  }    
  if (_create_ok)  
  {
    on_firm_change();
    on_config_change();
#if XVT_OS == XVT_OS_SCOUNIX
    do_events();
#endif
  }  
  else
    stop_run();
  break;
 case E_COMMAND:
  switch(ep->v.cmd.tag)
  {
  case M_FILE_QUIT:
    if (can_close())
      stop_run();
    break;
  case M_FILE_PG_SETUP:
    printer().set();
    break;
  case M_FILE_PRINT:
    print();
    break;
  case M_FILE_NEW:
    set_firm();
    break;
  case M_FILE_REVERT:
    if (config())
      on_config_change();
    break;
  case (M_FILE+11):
    about();
    break;
  default:
    if (ep->v.cmd.tag >= BAR_ITEM(1))
    {
      if(!menu(ep->v.cmd.tag))
        stop_run();
    }   
    break;
  }
  break;
 case E_CLOSE:
  if (can_close())
    stop_run();
  break;
 case E_QUIT:
  if (ep->v.query) 
  {
    if (can_close())
      xvt_app_allow_quit();
  } 
  else 
    stop_run();
  break;
default:
  break;
}

  return 0L;
}


void TApplication::stop_run()
{
  if (_savefirm) prefix().set_codditta(_savefirm);
  terminate();
  xvt_app_destroy();
}


bool TApplication::add_menu(TString_array& menu, MENU_TAG id)
{                                          
  TTemp_window tw(TASK_WIN);
  return tw.add_menu(menu,id,TRUE);
}

bool TApplication::remove_menu(MENU_TAG id)
{
  TTemp_window tw(TASK_WIN);
  return tw.remove_menu(id);
}


TApplication::TApplication() : _savefirm(0), _create_ok(FALSE)
  ,   _bar(TASK_MENUBAR)
{}


TApplication::~TApplication()
{}

bool TApplication::create()
{
  return TRUE;
}


bool TApplication::destroy()
{ 
  return TRUE;
}


void TApplication::terminate()
{
  close_all_dialogs();
  
  if (_create_ok)
  {
    destroy();                    // Distruzione files e maschere
#if XVT_OS == XVT_OS_WIN
    const word WM_WAKEUP = RegisterWindowMessage("WAKEUP");
    const HTASK ht = GetCurrentTask();
    SendMessage(HWND_BROADCAST, WM_WAKEUP, (unsigned int)ht, 0L);
    
    if (fexist("prassi.hlp"))
    {
      HWND hwnd = (HWND)xvt_vobj_get_attr(TASK_WIN, ATTR_NATIVE_WINDOW);
      WinHelp(hwnd, "prassi.hlp", HELP_QUIT, 0L);
    }  
#endif  
  }
  do_events();
  
  if (use_files())           
    free_global_vars();           // Distruzione variabili globali
  
  printer_destroy();  

  customize_controls(FALSE);      // Rilascio eventuali DLL
}


const char* TApplication::get_module_name() const
{
  TScanner scanner("prassi.aut");

  bool ok = FALSE;
  for (int aut = 0; scanner.line() != ""; aut++)
    if (strncmp(scanner.token(), _name, 2) == 0) { ok = TRUE; break; }

  TString module(scanner.token().mid(3));
  if (ok) ok = has_module(aut);
  

  if (!ok)                          
  {
    TToken_string em(extra_modules());
    const int items = em.items();
    if (items != 0)
      for (int j = 0; j < items; j++)
      {
        ok = has_module(em.get_int());
        if (!ok)
          break;
      }
    if (!ok) 
    {
      error_box("Il modulo '%s' non e' autorizzato", (const char*)module);
      module = "";
    }
  }  
  return module;
}


void TApplication::set_perms()
{   
  CGetAut(1);
  _dongle_aut.set(0, TRUE);
  for (int i = 1 ; i < ENDAUT; i++)
  {
    const int af = i - 1;
    const bool val = BITTEST(_int_tab0[af / 16], af % 16);
    _dongle_aut.set(i, val);
  }
  _user_aut.set(0, TRUE);
  
  const TString& utente = user();
  if (utente.not_empty())
  {
    if (utente == "PRASSI")
    {
      for (int i = 1 ; i < ENDAUT; i++)
        _user_aut.set(i);
    }
    else
    {
      TLocalisamfile users(LF_USER);
      
      users.zero();
      users.put("USERNAME", utente);
      if (users.read() == NOERR)
      {
        const TString& aut = users.get("AUTSTR");
        for (int i = aut.len()-1; i > 0; i--)
          _user_aut.set(i, aut[i] == 'X');
      }
    }
  }
}


void TApplication::check_parameters(int & argc, char* argv[])
{                         
  if (argc > 1)
  {
    const TFixed_string u(argv[argc-1]);
    if (u.compare("-u", 2, TRUE) == 0 || u.compare("/u", 2, TRUE) == 0)
    {
      user() = u.mid(2);
      argc--;
    }  
#ifdef DBG  
    else user() = "PRASSI";
#endif    
  }

#if XVT_OS == XVT_OS_WIN
  const long twin_style = WSF_ICONIZABLE | WSF_SIZE | WSF_CLOSE | WSF_MAXIMIZED;
  xvt_vobj_set_attr(NULL_WIN,ATTR_WIN_PM_TWIN_STARTUP_STYLE, twin_style);
#endif
}


void TApplication::run(int argc, char* argv[], const char* title)
{
  TFilename base(argv[0]);
  base.ext(""); base.lower();

  _title = title;

  if (user().empty())
    check_parameters(argc, argv);

  __argc = argc;
  __argv = (const char**)argv;

  int addbar = 0;
  if (argc > 1 && argv[1][0] == '-')
  {
    addbar = atoi(argv[1]+1);
    _name = cmd2name(argv[0], argv[1]);
  }
  else
  {
    addbar = 0;
    _name = cmd2name(argv[0]);
  }
  
  const int sn = get_serial_number();
  if (sn < 0)  
  {
    error_box("Perhaps you forgot to connect the dongle");
    return;
  }  
  
  if (use_files())
    init_global_vars();
  else
    CGetPref();           
  
  set_perms();

  const TFixed_string mod(get_module_name());
  if (mod.empty()) return;
  
  TString caption; caption << "PRASSI S.p.A. - " << mod;

  XVT_CONFIG cfg;
  cfg.base_appl_name = (char*)base.name();
  cfg.appl_name      = (char*)(const char*)_title;
  cfg.taskwin_title  = (char*)(const char*)caption;
  cfg.menu_bar_ID    = TASK_MENUBAR+addbar;
  cfg.about_box_ID   = 0;

  customize_controls(TRUE);

  _application = this;
  xvt_app_create(argc, argv, 0L, task_eh, &cfg);
}


// About box: risposta alla opzione Informazioni del menu File
void TApplication::about() const
{                                               
#include <prassi.ver>             
  const TFilename n(__argv[0]);
  message_box("PRASSI Versione %s\nProgramma %s\nLibreria del %s\nN.ro di serie %d-%s", 
              VERSION, (const char*)n.name(), __DATE__, SerNo, INTERNAL_VERSION);
}

// Risposta alla selezione Stampa del menu File
void TApplication::print()
{
#ifdef DBG
  error_box("Non saprei bene cosa stampare!");
#endif
}

void TApplication::check_menu_item(MENU_TAG item)
{
  xvt_menu_set_item_checked(TASK_WIN, item, TRUE);
  xvt_menu_update(TASK_WIN);
}

void TApplication::uncheck_menu_item(MENU_TAG item)
{
  xvt_menu_set_item_checked(TASK_WIN, item, FALSE);
  xvt_menu_update(TASK_WIN);
}


void TApplication::enable_menu_item(MENU_TAG item, bool on)
{
  xvt_menu_set_item_enabled(TASK_WIN, item, on);
  xvt_menu_update(TASK_WIN);
}

void TApplication::dispatch_e_menu(MENU_TAG item)
{
#if XVT_OS == XVT_OS_WIN
  HWND w = (HWND)xvt_vobj_get_attr(TASK_WIN, ATTR_NATIVE_WINDOW);
  PostMessage(w, WM_COMMAND, item, 0L);
#else
  ::dispatch_e_menu(TASK_WIN, item);
#endif  
}


bool TApplication::has_module(int module, int checktype) const
{
  bool ok = TRUE;
  if (checktype == CHK_ALL || checktype == CHK_DONGLE)
    ok = _dongle_aut[module];
  if (ok && checktype == CHK_ALL || checktype == CHK_USER)
    ok = _user_aut[module];
  return ok;
}


long TApplication::get_firm() const
{
  return prefix().get_codditta();
}

const char* TApplication::get_firm_dir() const
{
  return format("%s%s", __ptprf, prefix().name());
}


bool TApplication::set_firm(long newfirm)
{
  const long oldfirm = get_firm();

  if (newfirm < 1)
  {
    TMask mask("bagn002");
    TString80 pp(__ptprf); pp.cut(pp.len()-1);
    mask.set(F_PATHPREF, pp);

    mask.show(-2, extended_firm());

    disable_menu_item(M_FILE_NEW);
    const KEY k = mask.run();
    enable_menu_item(M_FILE_NEW);

    if (k == K_ENTER)
    {
      newfirm = mask.get_long(F_CODDITTA);
      const int tipodir = mask.get_int(F_TIPO);

      if (tipodir == 0 && !prefix().exist(newfirm) &&
          !build_firm_data(newfirm))
        return FALSE;
      if (tipodir > 0)
      {
        if (_savefirm == 0) _savefirm = oldfirm;   // E' necessario ricordare la ditta ...
        prefix().set(tipodir == 1 ? "com" : "");   // ... se si setta il prefix a com
        return TRUE;
      }
    }
  }

  if (newfirm == oldfirm || newfirm < 1)
    return newfirm > 0;

  if (prefix().test(newfirm))
  {
    prefix().set_codditta(newfirm);
    _savefirm = 0;
    
    WINDOW w = cur_win();
    if (w != NULL_WIN)
    {
      EVENT e;
      e.type = E_COMMAND;
      e.v.cmd.tag = M_FILE_NEW;
      e .v.cmd.shift = e.v.cmd.control = 0;
      xvt_win_dispatch_event(w, &e);
    }
    on_firm_change();
    on_config_change();
  }

  return TRUE;
}

bool TApplication::config()
  // gestisce le voci di configurazione
  // le si passa il file in cui cercare il proprio
  // paragrafo (comunque relativo alla ditta)
  // se non c'e', viene creato copiando il default
  // la variabile EdMask di quel paragrafo specifica
  // la maschera da usare
{
  TConfig cnf(CONFIG_DITTA);
  bool ok = FALSE;
  
  const TFilename maskname(cnf.get("EdMask"));
  if (maskname.empty())
    return warning_box("Nessun parametro da configurare");

  TMask m(maskname);
  
  // carica campi
  for (int i = 0; i < m.fields(); i++)
  {
    TMask_field& f = m.fld(i);
    const TFieldref* fref = f.field();
    if (fref != NULL)
    {
      const char* fname = fref->name();
      if (fname != NULL)
      {
        TString& oldvl = cnf.get(fname);
        if (!oldvl.empty())
          f.set(oldvl);
      }
    }
  }
  
  // run mask
  disable_menu_item(M_FILE_REVERT);
  
  if (m.run() == K_ENTER && m.dirty())
  {
    // aggiusta campi
    for (i = 0; i < m.fields(); i++)
    {
      TMask_field& f = m.fld(i);
      if (f.dirty())
      {
        const TFieldref* fref = f.field();
        if (fref != NULL)
          cnf.set(fref->name(), f.get(), NULL, TRUE);
      }
    }
    ok = TRUE;
  }
  
  enable_menu_item(M_FILE_REVERT);
  return ok;
}

void TApplication::set_cursor(bool w)
{ 
  static int _count = 0; 
  
  if (w) 
  {
    if (_count == 0)
      xvt_win_set_cursor(TASK_WIN, CURSOR_WAIT);
    _count++; 
  }     
  else 
  {
    _count--;
    CHECK(_count >= 0, "end_wait without matching begin_wait");
    if (_count == 0)
      xvt_win_set_cursor(TASK_WIN, CURSOR_ARROW);
  }  
}

// Ritorna TRUE se al programma corrente e' concesso cambiare ditta da menu.
// Praticamente controlla se e' stato lanciato da ba0 o dal program manager
bool TApplication::firm_change_enabled() const
{   
#if XVT_OS == XVT_OS_WIN
  static bool can = 2;
  if (can == 2)
  {
    TASKENTRY te; te.dwSize = sizeof(TASKENTRY); 
    HTASK ct = GetCurrentTask();
    TaskFindHandle(&te, ct);
    TaskFindHandle(&te, te.hTaskParent);
    can = stricmp(te.szModule, "BA0") == 0 ||
#ifdef DBG
      stricmp(te.szModule, "CVW4") == 0 ||
#endif    
        stricmp(te.szModule, "PROGMAN") == 0;
  }        
  return can;
#else
  return TRUE;
#endif  
}



void TApplication::on_firm_change()
{}

void TApplication::on_config_change()
{}


