#include <defmask.h>
#include <mask.h>
#include <relation.h>
#include <prefix.h>
#include <progind.h>
#include <sheet.h>

#include "ba1100.h"

// ORRIBILERRIMO
// ma chemmefotte?                       
HIDDEN TRectype*  __rec;
HIDDEN TRelation* __rel;
HIDDEN TMask*     __msk;

bool TEdit_file::memo_handler(TMask_field& f, KEY k)
{           
  bool ok = TRUE; 
  
  if (k == K_SPACE)
  {
    const int memoidx = f.dlg() - 400;
    
    // recuperate memo id and god (it.: godi)
    int mcnt = 0; 
    long val = -1l;
    
    for (int i = 0; i < __rec->items(); i++)
    {
      if (__rec->type(__rec->fieldname(i)) == _memofld)
      {
        if (memoidx == mcnt++)
        {
          val = __rec->get_long(__rec->fieldname(i));
          break;
        }
      }
    }
    
    ok = val != -1l;
    if (ok)
    {
      // edit memo with apposit maskerings 
      TMask mm("Edit campo memo", 1, 78, 20);
      mm.add_memo(501, 0, __rec->fieldname(i), 1, 1, 76,16);
      mm.add_button(DLG_OK, 0, "", -12, -1, 9, 2);
      mm.add_button(DLG_CANCEL, 0, "", -22, -1, 9, 2); 
      // build fieldref
      TString80 fref;              
      // UARNIN! Non funziona necessariamente per le tabelle
      // ma non abbiamo tabelle coi memo e  quindi camm' ifottamme'
      fref << __rec->num() << "->" << __rec->fieldname(i);      
      mm.field(501).set_field(fref);
      // se tutto va bene basta fare cosi' 
      mm.autoload(__rel);
      if (mm.run() == K_ENTER)    
      { 
        mm.autosave(__rel);  
        __msk->set (f.dlg() - 1,__rec->get(__rec->fieldname(i)));
      }
      // se invece va male, l'e' istes
    }    
  }
  return ok;
}                                      

bool TEdit_file::browse(int logicnum, const char* name)
{
  TRelation relation(logicnum);
  TCursor cursor(&relation);
  TRectype& curr = cursor.curr();
  TRectype svrec(cursor.curr());
  
  TToken_string head(256);
  TToken_string trac(256);
  
  // DIO CHE ORRORE! MA CHECCEPOSSOFA'?                 
  __rel = &relation;                      
  // E POI, DICIAMOLO, CHEMMEFOTTAMME'?
  
  const char* n;
  trac.add("");
  head.add("@1");

  for(int i = 0; (n = curr.fieldname(i)) != NULL; i++)
  {
    trac.add(n);
    
    TString16 name(n); name.lower(); name[0] = toupper(name[0]);
    head.add(name);
    
    TFieldtypes t = curr.type(n);
    const int len = (t == _datefld) ? 10 : curr.length(n);
    head << '@' << max(len, (int)strlen(n));
    if (t == _realfld || t == _intfld || t == _longfld || t == _wordfld || t == _realfld) 
      head << 'R';
  }

  const bool superprassi = user() == "PRASSI";
  
  KEY ch;
  TCursor_sheet sheet(&cursor, trac, name, head, superprassi ? 6 : 0);
  sheet.maximize();

  while ((ch = sheet.run()) != K_ESC)
  {     
    if (!superprassi)
    {            
      error_box("Funzione non ammessa per l'utente %s", (const char*)user());
      ch = K_ESC;
    }
    
    if (ch == K_DEL && sheet.one_checked())
    {
      TProgind* pind = NULL;
      cursor.freeze(TRUE);
      bool go = FALSE;
      bool first = FALSE;
      int j;
      for (j = 0, cursor = 0; j < sheet.items(); ++cursor, j++)
      {
        if (sheet.checked(j))
        {
          if (!go && !first) 
            go = yesno_box("Si desidera cancellare i %d record indicati?", sheet.checked());
          first = TRUE; 

          if (!pind)
          {
            pind = new TProgind(sheet.checked(),"Attendere...",
                                TRUE, TRUE, 32);
            pind->addstatus(1);
          }
          else 
          {
            if (pind->iscancelled()) break;
            pind->addstatus(1);
          }  

          if (go) cursor.file().remove();
          sheet.uncheck(j);
        }
      }
      if (pind) delete pind;
      cursor.freeze(FALSE);
      
      if (first) {sheet.select(1); continue;}
    }
    if (ch == K_ENTER || ch == K_DEL) 
      cursor = sheet.selected();
    
    switch(ch)
    {
    case K_ENTER:  // edit fields
      svrec = curr;
      if (edit_record(curr, FALSE) == K_ENTER)
      {
        TString s(svrec.key(1));

        if (s != curr.key(1))
        {
          cursor.file().write();
          if (cursor.file().good())
          {
            curr = svrec;
            cursor.file().remove();
          }
        }
        else
          cursor.file().rewrite();
      }
      break;
    case K_DEL:    // delete record
      if (yesno_box("Confermare la cancellazione del record"))
        cursor.file().remove();
      break;
    case K_CTRL+'N':    // insert new record
      curr.zero();
      if (edit_record(curr,FALSE) == K_ENTER)
        cursor.file().write();
      break;
    default:
      break;  
    }
    sheet.force_update();
  }
  return K_ESC;
}

KEY  TEdit_file::edit_record(TRectype& rec, bool readonly)
{
  for(int recs = 0; rec.fieldname(recs) != NULL; recs++);
  
  const int fpp = 16;                               // Fields per page
  const int rows  = recs > fpp ? 20 : recs+4;
  const int pages = recs/fpp + (recs % fpp ? 1 : 0);
  TMask m("Modifica record", pages, 78, rows);
  
  int curpage = 0, currow = 1, nid = 100;
  const char* cp;
  int mcnt =0;
  
  for(int i = 0; (cp = rec.fieldname(i)) != NULL; i++)
  {
    // add fields ONE by ONE
    TString16 s(cp); s.left_just(16);
    const int len = rec.length(cp);
    switch (rec.type(cp))
    {
    case _alfafld:
      m.add_string(nid++,curpage, s, 3, currow, len, "", len > 50 ? 50 : len);
      break;
    case _intfld:
    case _longfld:
    case _wordfld:
    case _realfld:
      m.add_number(nid++, curpage, s, 3, currow, len, "R", rec.ndec(cp));
      break;
    case _datefld:
      m.add_date(nid++, curpage, s, 3, currow);
      break;
    case _charfld:
    case _boolfld:
      m.add_string(nid++,curpage, s, 3, currow, 1);
      break;
    case _intzerofld:
    case _longzerofld:
      m.add_number(nid++, curpage, s, 3, currow, len, "Z", rec.ndec(cp));
      break;
    case _memofld:
      m.add_zoom( nid++, curpage, s, 3, currow, 50, "", 50 );
      // memo del caz: add bottone per l'editing etc
      // m.add_button (400+(mcnt++), curpage, "Edit", 35, currow, 9, 1);   
      // __rec = &rec;             
      // __msk = &m;
      // m.set_handler(400+(mcnt-1), memo_handler);
      break;
    default:
      break;
    }
    
    m.field(nid-1).set(rec.get(cp));
    
    if (((i+1) % fpp) == 0 || i == recs-1) 
    { 
      m.add_button(DLG_OK, curpage, "", -12, -1, 9, 2);
      m.add_button(DLG_CANCEL, curpage, "", -22, -1, 9, 2);
      curpage++; currow = 1;
    }
    else currow++;
  }

  if (readonly)
  {
    const int max = m.fields();
    for (int i = 0; i < max; i++)
    {
      TMask_field& f = m.fld(i);
      if (f.class_id() != CLASS_BUTTON_FIELD)
        f.disable();
    }
  }

  const KEY k = m.run();

  if (k == K_ENTER && !readonly)
  {
    nid = 100;
    for(i = 0; (cp = rec.fieldname(i)) != NULL; i++)
      rec.put(cp, m.get(nid++));
  }

  return k;
}



