#include "mktest.h"

void menutest(void) {

  h_Menu hmenu;
  h_File hfile;
  h_Font * fonttab;
  short nb_font;
  h_Font * font_message;
  HANDLE h;
  HANDLE h_level;
  HANDLE hvar;
  short key;
  unsigned char * data;
  HSym hsym;
  unsigned short size,size2;
  unsigned short size_data;
  clrscr();
  
  nb_font=hl_loadAllFont(&fonttab);
  
  font_message=hl_findFont("tios1",fonttab,nb_font);
  
  printf("h_object=%lu\nh_bkmk=%lu\nh_menulevel=%lu\nh_scrline=%lu\n",sizeof(h_Object),sizeof(h_Bookmark),sizeof(h_MenuLevel),sizeof(h_ScrLine));
  ngetchx();

  h_initMenuVAT(&hmenu,font_message,10,20,LCD_WIDTH-20,10,&h,&h_level,NULL,NULL);
  
  clrscr();
  
  h_initSynchro(SPEED_KEY);
menu_redraw:
  hl_drawMenu(&hmenu,LCD_SCREEN);
  do {  
    h_waitSynchro();
    key=0;
    if (K_DOWN) {
      h_startSynchro(SPEED_KEY);
      if (K_DIAM) {  //to the bottom
        hl_goMenuBottom(&hmenu);
      } else if (K_2ND) {  //1 page scroll
        hl_goMenuPageDown(&hmenu);
      } else {
        hl_goMenuDown(&hmenu);
      }
      goto menu_redraw;
    } else if (K_UP) {
      h_startSynchro(SPEED_KEY);
      if (K_DIAM) {  //go to the top
        hl_goMenuTop(&hmenu);
      } else if (K_2ND) { //go back one page
        hl_goMenuPageUp(&hmenu);
      } else {
        hl_goMenuUp(&hmenu);
      }
      goto menu_redraw;
    } else if (K_ENTER) {  //[ENTER] : the choice is done
      h_startSynchro(SPEED_KEY);
      key=hmenu.no_choice+1;
    } else if (K_ESC) {  //[ESC] : cancel
      h_startSynchro(SPEED_KEY);
      goto quit;
    } else {
      h_saveEnergy();
    }
  } while (key==0);
  
  h_waitSynchro();
  h_freeSynchro();
  
  hsym = ((HSym *)hmenu.tab)[key-1];
  
  hvar=DerefSym(hsym)->handle;
  
  if (h_getFileType(HeapDeref(hvar))==TEXT_TAG) {
    data=HLock(hvar);
    size_data=*(unsigned short *)data;
    hl_parse(&hfile,data+4,size_data-3);
    hl_layout(&hfile,LCD_WIDTH,FALSE,fonttab,nb_font,NULL,NULL);
    size = 0;
    size+=hfile.nb_objs*sizeof(h_Object);
    size+=hfile.nb_bkmks*sizeof(h_Bookmark);
    size+=hfile.nb_bkmks*sizeof(h_MenuLevel);
    size2=size+hfile.nb_bkmks*sizeof(h_ScrLine);
    printf("ini=%d htxt=%d data=%d,%d \n",size_data,hfile.size_text,size,size2);
    size+=hfile.size_text;
    size2+=hfile.size_text;
    printf("diff = %d (%ld %%) , %d (%ld %%)",size - size_data,(((long)(size - size_data))*100) / size_data,size2 - size_data,(((long)(size2 - size_data))*100) / size_data);
    ngetchx();
    hl_freehFile(&hfile);
    HeapUnlock(hvar);
    goto menu_redraw;
  }

quit: 
  HeapFree(h);
  HeapFree(h_level);
  hl_unloadAllFont(fonttab,nb_font);

  
}
  
  
  
void testmkhtxt(void) {
  
  menutest();
  
}