#include "clip.h"

#define APPNAME	"MyApp"

LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);
void app_proc();

HINSTANCE hinst;
HWND mainwnd;

#define DISP_X	256
#define DISP_Y	256
unsigned char vbuff[DISP_X * DISP_Y];
unsigned char zbuff[DISP_X * DISP_Y];
SURFACE surface = { DISP_X, DISP_Y, vbuff, zbuff };
RENDER render;
#define Tcur (&render.context->matrix), (&render.context->matrix)

int
main()
{
	int bw, bh;
	WNDCLASS wc;
	RECT wr, cr;
	MSG msg;

	hinst = GetModuleHandle(NULL);

	pceLCDSetBuffer((PIECE_VRAM*)&surface);

	memset(&wc, 0, sizeof wc);
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = wndproc;
	wc.hInstance = hinst;
	wc.hCursor = LoadCursor(NULL, IDC_CROSS);
	wc.lpszClassName = APPNAME;
	RegisterClass(&wc);

#define SCALE 1
	mainwnd = CreateWindow(APPNAME, APPNAME,
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
		NULL, NULL, hinst, NULL);
	GetWindowRect(mainwnd, &wr);
	GetClientRect(mainwnd, &cr);
	bw = (wr.right - wr.left) - (cr.right - cr.left);
	bh = (wr.bottom - wr.top) - (cr.bottom - cr.top);
	MoveWindow(mainwnd, 0, 0, bw + DISP_X * SCALE, bh + DISP_Y * SCALE, FALSE);
	ShowWindow(mainwnd, SW_SHOW);
	UpdateWindow(mainwnd);

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

RGBQUAD palette[256] = {
	{ 255, 0, 0, 0 },
	{ 192, 0, 0, 0 },
	{ 128, 0, 0, 0 },
	{  64, 0, 0, 0 },
	{ 0, 255, 0, 0 },
	{ 0, 192, 0, 0 },
	{ 0, 128, 0, 0 },
	{ 0,  64, 0, 0 },
	{ 0, 0, 255, 0 },
	{ 0, 0, 192, 0 },
	{ 0, 0, 128, 0 },
	{ 0, 0,  64, 0 },
	{ 0, 255, 255, 0 },
	{ 0, 192, 192, 0 },
	{ 0, 128, 128, 0 },
	{ 0,  64,  64, 0 },
};

LRESULT CALLBACK
wndproc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
	static int run;
	PAINTSTRUCT ps;
	HDC hdc;
	RECT rc;

	switch(msg) {
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	case WM_PAINT:
		hdc = BeginPaint(hwnd, &ps);
		SetStretchBltMode(hdc, COLORONCOLOR);
		GetClientRect(hwnd, &rc);
		pceLCDTrans(hdc, 0, 0, rc.right, rc.bottom, 0, 0, 0, 0, /*palette*/NULL);
		EndPaint(hwnd, &ps);
		return 0;
	case WM_TIMER:
		app_proc();
		InvalidateRect(hwnd, NULL, FALSE);
		return 0;
	case WM_KEYDOWN:
		switch(wparam) {
		case VK_ESCAPE:
			SendMessage(hwnd, WM_CLOSE, 0, 0);
			return 0;
		case VK_RETURN:
			run = !run;
			if(run) {
				SetTimer(hwnd, 1, 1, NULL);
			} else {
				KillTimer(hwnd, 1);
			}
			return 0;
		case VK_SPACE:
			SendMessage(hwnd, WM_TIMER, 0, 0);
			return 0;
		}
		break;
	}
	return DefWindowProc(hwnd, msg, wparam, lparam);
}

/****************************************************************************/

#include "tex.c"
TEXTURE tex;

void
app_proc()
{
	DRAW_OBJECT obj;

	memset(vbuff, 0, sizeof vbuff);

	texture_init(&tex, TEX);
	pceLCDSetObject(&obj, &tex, 0, 0, 0, 0, 256, 256, DRW_NOMAL);
	pceLCDDrawObject(obj);
}
