/*
   viewer for birthdays in Windows
*/

#include <string.h>
#include <stdio.h>

#include "birthday.h"

#ifdef DOS
#include "getopt.h"
/* getopt.h only declares this if we have GCC */
extern int getopt (int argc, char *const *argv, const char *shortopts);
#else /* DOS */
#include <unistd.h>
#endif /* DOS */

#define STRICT
#include <windows.h>
#include <windowsx.h>

#include <ctl3d.h>

#define IDD_LIST 101 // list box in dialog

BOOL CALLBACK ListDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
LRESULT NewWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

HINSTANCE hInstance;
HWND hDialog;

void setaresome(char *s);
void adddlgstr(char *str);
int aresome;

#pragma argsused
int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hinstPrev, LPSTR lpszCmdLine, int iShow)
{
   char *fname = NULL;
   struct event *evl; /* evl => event list */
   unsigned i;
   HINSTANCE hInstDPCLib;
   int aresome;
   int argc;
   char *argv[128]; /* 128 cmdline args max --- should be enough! */
   char *p1,*p2;

   /* make argc, argv. Not too robust ... */
   argv[0]="bdwin.exe";
   for(argc=1,p1=p2=(char *)lpszCmdLine; *p1!=0 && argc < 128; p1++) {
     if (*p1 == ' ') {
       *p1=0;
       argv[argc++]=(char *) p2;
       p2=p1++;
     }
   }

   if (p1 != (char *)lpszCmdLine) {
     *p1=0;
     argv[argc++]=(char *) p2;
   }

   argv[argc]=NULL;

   hInstance = hInst;

   hInstDPCLib = LoadLibrary("dpclib.dll");

   Ctl3dRegister(hInstance);
   Ctl3dAutoSubclass(hInstance);

  while ((i = getopt (argc, argv, "f:W:M:m:")) != -1)
    switch (i)
      {
      case 'f':
	fname=strdup(optarg);
	break;
      case 'W':
	iDWarn = atoi(optarg);
	break;
      case 'M':
	iMaxWarn = atoi(optarg);
	break;
      case 'm':
	iMinWarn = atoi(optarg);
	break;
      default:
	fatal("Internal error: unprocessed option %c\n", i);
      }

   evl = readlist(fname); /* read and format entries */

   /* NB aresome is global */
   aresome=0;
   liststrings(evl, setaresome);

   if (aresome == 0) {
      MessageBox(NULL, "No Birthdays for a While", "DPC Birthday Viewer", MB_OK);
   } else {
      DialogBoxParam(hInst, "ListDialog", NULL, ListDlgProc, (LPARAM) evl);
   }

   Ctl3dUnregister(hInstance);
   FreeLibrary(hInstDPCLib);

   return 0;
}

#pragma argsused
BOOL CALLBACK ListDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
   int i;
   WNDPROC lpNewProc;

   switch(uMsg) {
   case WM_INITDIALOG: {
     struct event *evl=(struct event *)lParam;

     hDialog=hDlg;
     liststrings(evl, adddlgstr);
     return TRUE;
   }
   case WM_COMMAND:
      if (wParam == IDOK) EndDialog(hDlg, 0);
      return TRUE;
   }
   return FALSE;
}

void setaresome(char *s)
{
  aresome=1;
}

void adddlgstr(char *str)
{
  ListBox_AddString(GetDlgItem(hDialog, IDD_LIST), str);
}
