// a little C lib to keep simple Win32 applications a little more "DRY"
// will probably only compile with MinGW GCC

#include <windows.h>
#include "w32dry.h"
#include <stdio.h> // for sprintf

void init_window_classex(PWNDCLASSEX class,
                         window_instance *win,
                         HINSTANCE hInstance,
                         WNDPROC WndProc,
                         LPCSTR name)
{
  WNDCLASSEX mine = {    // What a fucking pain in the ass.
    // never changing:
    .cbSize = sizeof(WNDCLASSEX),
    .style = 0,
    .cbClsExtra = 0,
    .cbWndExtra = 0,

    // supplied by user:
    .lpfnWndProc = WndProc,
    .hInstance = hInstance,
    .lpszClassName = name,

    // sensible defaults:
    .hIcon = LoadIcon(NULL, IDI_APPLICATION),
    .hCursor = LoadCursor(NULL, IDC_ARROW),
    .hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH),
    .lpszMenuName = NULL,
    .hIconSm = LoadIcon(NULL, IDI_WINLOGO),
  };

  *class = mine;
  win->class = class;
  win->hWnd = NULL;
  win->title = "Anonymous coward window";  // default value
  win->style = WS_OVERLAPPEDWINDOW;
  win->x = win->y = CW_USEDEFAULT;
}

int create_window(window_instance *win, int width, int height)
{
  win->hWnd = CreateWindow(win->class->lpszClassName,
                           win->title,
                           win->style,
                           win->x, win->y,
                           width, height,
                           NULL,    // parent handle
                           NULL,    // menu handle
                           win->class->hInstance,
                           NULL);
  return !!win->hWnd;
}

int message_loop()
{
  MSG msg;

  // params: message, hWnd, first, last
  while (GetMessage(&msg, NULL, 0, 0) > 0) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
  return msg.wParam;
}

int _check(char *contents, int result)
{
  char errcodespace[32];
  if (result) return result;
  MessageBox(NULL, contents, "fatal _check error: this code failed", MB_OK);
  sprintf(errcodespace, "error code %d", (int)GetLastError());
  MessageBox(NULL, errcodespace, "here's why", MB_OK);
  ExitProcess(1);
}
