#include <windows.h>
#include <commctrl.h>
#include <vfw.h>
#include <math.h>
#include <stdlib.h>
#include <string.h> 
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <malloc.h>
#include "win-menu.h"
#include "win-main.h"
#include "gcore/gcomm.h"
#include "gsys/cfc.h"
#define MANAGE_HELP_WINDOW
#ifdef MANAGE_HELP_WINDOW
#include "sic/getcar.h"
#endif // MANAGE_HELP_WINDOW
#include "gcore/glaunch.h"
#include "ggui\gmenu.h"

#define NMENUCOMMAND 1024
static char *menucommand[NMENUCOMMAND];

HINSTANCE hInst; // current instance
int screenwidth;

int lastid;

#ifdef MANAGE_HELP_WINDOW
HWND win_help = NULL, helpedit; // fenetre de help de la barre de menu
char *helptext;
#endif // MANAGE_HELP_WINDOW

LRESULT APIENTRY MenuWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
  switch (message) {
#ifdef MANAGE_HELP_WINDOW
  case WM_CREATE:
	 if (strlen((LPSTR) lParam) != 0) {
	  helpedit = CreateWindow("RICHEDIT", NULL,       
							   WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_BORDER |
							   ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY, 
							   0, 0, 0, 0, /* set size in WM_SIZE message  */ 
						       hwnd, (HMENU) NULL, hInst, (LPSTR) NULL);
      
	  
	  SendMessage(helpedit, WM_SETTEXT, 0, (LPARAM) helptext);
	  free(helptext);
    }
	break;
  case WM_SIZE:
	if (hwnd == win_help)
	  MoveWindow(helpedit, 0, 0, LOWORD(lParam), HIWORD(lParam), TRUE /* Repaint */);
	break;
#endif // MANAGE_HELP_WINDOW
  case WM_CLOSE:
	ShowWindow(hwnd, SW_HIDE);
	return 0;
  case WM_COMMAND:{
	WORD idcom = LOWORD(wParam) - 100;

    if ((idcom>=0) && (idcom < lastid)) {
		sic_post_command_text(menucommand[idcom]);
	}
	if (idcom == lastid) {
#ifdef MANAGE_HELP_WINDOW
	    struct _stat statb;
	    FILE *fd;
	    size_t numread;

		if (_stat(xgag_get_detach_name(), &statb) == -1) {
          helptext = (char *) malloc(80*sizeof(char));
          sprintf(helptext, "%s", "Not found ..."); 
        }
        else {
          fd = fopen(xgag_get_detach_name(), "r");
          helptext = (char *) malloc((unsigned)(statb.st_size+1));
          numread = fread(helptext, sizeof(char), statb.st_size+1, fd);
		  //printf( "Number of bytes read = %d\n", numread );

          helptext[statb.st_size] = 0;
          fclose(fd);
        }
        if (win_help == NULL) {
		  win_help = CreateWindowEx(WS_EX_TOOLWINDOW, TEXT("sicmenu"), xgag_get_detach_name(),  
						            WS_OVERLAPPEDWINDOW,
									CW_USEDEFAULT, CW_USEDEFAULT,
						  			600, 300,
									(HWND) NULL, (HMENU) NULL, hInst, (LPSTR) "helptest");
	      ShowWindow(win_help, SW_SHOWNORMAL);
		  SetForegroundWindow(win_help);
	    }
		else {
		  ShowWindow(win_help, SW_SHOW);
          SetForegroundWindow(win_help);
		}
#endif // MANAGE_HELP_WINDOW

        
	}
	
	

	}
	break;
    
  default:
	return (DefWindowProc(hwnd, message, wParam, lParam));
	break;
  }
  return 0;

}

static void run_win_menu(const char *tempfilename) 
{
  
  HMENU hMenu, hPopupMenu;
  HWND win_menu;
  RECT rect;
  MSG msg;
  char wintitle[256]; 
  char winhelpfile[256];
  char line[256];
  char label[256];
  int i = 0;
  FILE *fd;
  //HDC hdcScreen;
  fd = fopen(tempfilename, "r");

  fgets(line, 256, fd);
  strncpy(wintitle, line, strlen(line) - 1);
  wintitle[strlen(line)-1] = 0 ; // SG, otherwise bad trailing characters
  fgets(line, 256, fd);
  strncpy(winhelpfile, line, strlen(line) - 1);
  winhelpfile[strlen(line)-1] = 0 ; // SG, otherwise bad trailing characters
  
  hMenu = CreateMenu();

  while (fgets(line, 256, fd) != NULL) {
    if (strncmp(line, "MENU", 4) == 0) {
      fgets(line, 256, fd);

      strncpy(label, line, strlen(line)-1);
      label[strlen(line) - 1] = 0;

	  hPopupMenu = CreatePopupMenu();
	  AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT_PTR) hPopupMenu, label);

	  for (;;) {
	    fgets(line, 256, fd);
	    if (strncmp(line, "ENDMENU", 7) == 0) break;

	    strncpy(label, line, strlen(line)-1);
	    label[strlen(line) - 1] = 0;
	    AppendMenu(hPopupMenu, MFT_STRING, 100+i, label);

		fgets(line, 256, fd);
        menucommand[i] = (char *)malloc( strlen( line));
        strncpy( menucommand[i], line, strlen( line) - 1);
        menucommand[i][strlen( line) - 1] = 0;

		i++;
      }
	}
	else {
	  strncpy(label, line, strlen(line)-1);
      label[strlen(line) - 1] = 0;
      AppendMenu(hMenu, MFT_STRING, 100+i, label);

      fgets(line, 256, fd);
      menucommand[i] = (char *)malloc( strlen( line));
	  strncpy(menucommand[i], line, strlen(line)-1);
      menucommand[i][strlen(line) - 1] = 0;

	  i++;
    }
  }
	
  AppendMenu(hMenu, MFT_STRING, 100+i, "Help");
  lastid = i;
  fclose(fd);
  if (unlink(tempfilename) == -1) MyErrorHandler("_unlink", "run_win_menu");
  
  rect.left = 0;
  rect.right = screenwidth -2*GetSystemMetrics(SM_CXFIXEDFRAME);
  rect.top = rect.bottom = 0;
  AdjustWindowRect(&rect, WS_CAPTION, 1 /* Menu present*/);

  win_menu = CreateWindowEx(0, TEXT("sicmenu"), wintitle,  
						  WS_CAPTION | WS_SYSMENU,
					      0, 0,
						  rect.right - rect.left, rect.bottom - rect.top,
						  (HWND) NULL, hMenu, hInst, (LPSTR) NULL);
 
  ShowWindow(win_menu, SW_SHOWNORMAL);
  SetForegroundWindow(win_menu);
  //UpdateWindow(win_menu);

  while (GetMessage(&msg, NULL, 0, 0)) { 
   TranslateMessage(&msg);
   DispatchMessage(&msg); 
  }
}

void init_menu( HANDLE hInstance)
{
    WNDCLASS  wc;
    HDC hdcScreen;

    hInst = hInstance;

    wc.style = 0;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInst;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = GetStockObject(LTGRAY_BRUSH);
    wc.lpszMenuName = NULL; 

    wc.lpfnWndProc = (WNDPROC)MenuWndProc;
    wc.lpszClassName = TEXT("sicmenu");
    if (!RegisterClass(&wc)) MyErrorHandler("RegisterClass", "DllMain");

    hdcScreen = CreateDC("DISPLAY", (LPCSTR) NULL, 
        (LPCSTR) NULL, (CONST DEVMODE *) NULL); 

    screenwidth = GetDeviceCaps(hdcScreen, HORZRES);
    //printf("screenwidth %d screenheight %d\n", screenwidth, screenheight);
    DeleteDC(hdcScreen);

    set_menu_handlers( run_win_menu, NULL);
}
