#include "xuserwnd.h"
#include "xcntrevn.h"

#include "xmsgbox.h"
MRESULT userProc(HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
{
   XUserWindow * win = ( XUserWindow *) WinQueryWindowPtr( hwnd, 0);
   if( msg == WM_CREATE)
     {
        win = (XUserWindow*) mp1;
        mp1 = 0;
        WinSetWindowPtr( hwnd, 0, win);
        return WinDefWindowProc( hwnd, msg, mp1, mp2);
     }

   if(win)
     {
       switch( msg )
         {
            case WM_COMMAND:
              win->DoCommand( SHORT1FROMMP(mp1));
              return 0;
            case WM_CONTROL:
              {
                 XControlEvent e(win, mp1, mp2);
              }
              return 0;
            case WM_PAINT:
              win->Draw();
              return WinDefWindowProc( hwnd, msg, mp1, mp2);
            default:
              {
                 BOOL handled = FALSE;
                 MRESULT mr = HandleDefault( win, msg, mp1, mp2, handled);
                 if( handled )
                    return mr;
              }
         }
     }
  return WinDefWindowProc( hwnd, msg, mp1, mp2);
}


XUserWindow :: XUserWindow ( XWindow * w)
{
  XUserWindow(w->GetClientHandle());
}


XUserWindow :: XUserWindow ( LONG handle)
{
   HAB hab = WinQueryAnchorBlock(handle);
   static BOOL userRegistered = FALSE;

   if(userRegistered == FALSE)
      {
         WinRegisterClass( hab, (PSZ) "OOL_USERCLASS", (PFNWP) userProc, 0, 4);
         userRegistered = TRUE;
      }

   winhandle = WinCreateWindow(handle, (PSZ) "OOL_USERCLASS", (PSZ)"",
                        WS_VISIBLE | FS_SCREENALIGN,
                        0, 0, 0, 0,
                        handle, HWND_TOP, 0, this, 0);
}


XUserWindow :: ~XUserWindow()
{
   HWND hwnd;

   HENUM enumWindow = WinBeginEnumWindows(winhandle);
   while( (hwnd = WinGetNextWindow( enumWindow)) != NULLHANDLE)
      {
          XWindow * w = (XWindow *) WinQueryWindowPtr( hwnd, 0);
          if(w && w != this)
             delete w;
      };
   WinEndEnumWindows( enumWindow);
   WinDestroyWindow( winhandle );
}


