#include <stdio.h>
#include <windows.h>

const int width = 640;
const int height = 480;
char screen[width*height * 4];

void draw_screen() {
	// Draw to the screen!
}

LRESULT WINAPI WindowProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
	switch (message) {
	case WM_CHAR: DestroyWindow(window); break;
	case WM_ERASEBKGND: return 1;
	case WM_DESTROY: PostQuitMessage(0); return 0;
	case WM_PAINT: {
			PAINTSTRUCT ps;
			HDC dc = BeginPaint(window, &ps);
			PatBlt(dc, 0, 0, 4096, 4096, BLACKNESS);
			EndPaint(window, &ps);
		}
		return 0;
	}
	return DefWindowProc(window, message, wparam, lparam);
}

//int PASCAL WinMain(HINSTANCE instance, HINSTANCE previous_instance, LPSTR cmd_line, int cmd_show) {
int main() {
	WNDCLASSA wc = { 0 };
	wc.lpfnWndProc = WindowProc;
	wc.hInstance = 0;
	wc.lpszClassName = "jo_win_shim";
	RegisterClass(&wc);
	HWND window = CreateWindowA("jo_win_shim", "jo_win_shim", WS_CAPTION | WS_POPUP | WS_CLIPCHILDREN | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SIZEBOX, 64, 64, 64, 64, 0, 0, 0, 0);

	// Calculate the extra width and height for the window.
	RECT r, c;
	GetWindowRect(window, &r);
	GetClientRect(window, &c);
	int extra_width = (r.right - r.left) - (c.right - c.left);
	int extra_height = (r.bottom - r.top) - (c.bottom - c.top);

	SetWindowPos(window, 0, 0, 0, width + extra_width, height + extra_height, SWP_NOMOVE);
	ShowWindow(window, SW_SHOWDEFAULT);

	while (true) {
		MSG msg;
		if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
			if (msg.message == WM_QUIT)
				exit(0);
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		} else {
			draw_screen();
			unsigned bmi_data[sizeof(BITMAPINFOHEADER)/4 + 3];
            BITMAPINFO *bmi = (BITMAPINFO*)bmi_data;
			bmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
			bmi->bmiHeader.biWidth = width;
			bmi->bmiHeader.biHeight = -height;
			bmi->bmiHeader.biPlanes = 1;
			bmi->bmiHeader.biBitCount = 32;
			bmi->bmiHeader.biCompression = BI_BITFIELDS;
            *(unsigned*)&bmi->bmiColors[0] = 255 << 0;
            *(unsigned*)&bmi->bmiColors[1] = 255 << 8;
            *(unsigned*)&bmi->bmiColors[2] = 255 << 16;
			HDC dc = GetDC(window);
			GetClientRect(window, &c);
            SetStretchBltMode(dc, STRETCH_HALFTONE);
			StretchDIBits(dc, c.left, c.top, c.right, c.bottom, 0, 0, width, height, screen, bmi, DIB_RGB_COLORS, SRCCOPY);
			ReleaseDC(window, dc);
		}
	}
	return 0;
}
