//      $Id: brwapp.cpp,v 1.4 1995-04-21 10:47:17 nik Exp $        

#include <brwapp.h>
#include <mailbox.h>
#include <utility.h>

///////////////////////////////////////////////////////////
// TBrowse_application
///////////////////////////////////////////////////////////

bool TBrowse_application::main_loop()
{
  long recins = -1;

  query_mode();
  curr_mask().open_modal();

  KEY k;
  
  // Provoca l'autopremimento per il messaggio di LINK
  if (lnflag()) curr_mask().send_key(K_AUTO_ENTER, 0);
  
  do
  {
    // Dis/abilita cambio ditta
    enable_menu_item(M_FILE_NEW, (curr_mask().mode() == MODE_QUERY));
    
    k = curr_mask().run();

    // Seleziona il cursore a clessidra se necessario
    if (k != K_QUIT && k != K_F9) 
      begin_wait();

    switch (k)
    {
    case K_ESC:
      if (curr_mask().edit_mode()) 
        file().reread(_unlock); // Unlock main file

      if (curr_mask().query_mode()) 
      {
        curr_mask().reset();
        set_fixed();
      }  
      else query_mode();
      if (lnflag()) k = K_QUIT;
      break;                             
    case K_QUIT:      
      if (curr_mask().mode() == MODE_MOD && 
          (autoins_caller().not_empty() || lnflag()))
        recins = file().recno();
      break;
    case K_ENTER:
      if (find(0)) modify_mode();
      else message_box("Registrazione assente"); // ocio
      break;
    case K_F9:
      search_mode();
      break;
    default:
      setkey();
      int err = ~NOERR;
      switch (k)
      {
      case K_HOME:
        err = file().readat(first(), _testandlock);
        break;
      case K_NEXT:
        err = file().reread();
        err = file().next(_testandlock);
        break;
      case K_PREV:
        err = file().reread();
        err = file().prev(_testandlock);
        break;
      case K_END:
        err = file().readat(last(), _testandlock);
        break;
      default:
        break;
      }
      if (err == NOERR || err == _islocked) modify_mode();
      else query_mode();
      break;
    }
    
    if (k != K_QUIT && k != K_F9) 
      end_wait(); 
  } while (k != K_QUIT);

  if (curr_mask().is_open())
    curr_mask().close_modal();

  curr_mask().set_mode(NO_MODE);

  if (recins > 0 && autoins_caller().not_empty())
  {
    TMessage msg(autoins_caller(), MSG_AI, format("%ld", recins));
    msg.send();
  }
  if (recins > 0 && lnflag())
  {
    TMessage msg(autoins_caller(), MSG_LN, format("%ld", recins));
    msg.send();
  }

  return k != K_QUIT;
}
