#include "VideoWnd.h"

TCHAR		g_szVideoWndClassName[]		= TEXT("VideoWndClass");

VOID DefineVideoWndClass(LPWNDCLASSEX lpWc)
{
	lpWc->cbSize			= sizeof(WNDCLASSEX);
	lpWc->style				= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	lpWc->lpfnWndProc		= VideoWndProc;
	lpWc->cbClsExtra		= 0;
	lpWc->cbWndExtra		= sizeof(LPVIDEOWND);
	lpWc->hIcon				= NULL;
	lpWc->hCursor			= LoadCursor(NULL, IDC_ARROW);
	lpWc->hbrBackground		= (HBRUSH)(COLOR_WINDOWTEXT+1);
	lpWc->lpszMenuName		= NULL;
	lpWc->lpszClassName		= g_szVideoWndClassName;
	lpWc->hIconSm			= NULL;
}

LRESULT CALLBACK VideoWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch(uMsg)
	{	
	case WM_CREATE:
		{
			LPVIDEOWND			lpVw = (LPVIDEOWND)HeapAlloc(g_hProcHeap, HEAP_ZERO_MEMORY, sizeof(VIDEOWND));
			
			SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)lpVw);
		}
		break;

	case VWM_SETFRAME:
		{
			LPWVFRAME	lpWvf	= (LPWVFRAME)lParam;
			LPVIDEOWND	lpVw	= (LPVIDEOWND)GetWindowLongPtr(hwnd, GWLP_USERDATA);
			HDC			hdc;
			INT			iX, iY;
			INT_PTR		pPos;			

			if(lpWvf == NULL)
				return 0;

			lpVw->iOrigW = lpWvf->iWidth;
			lpVw->iOrigH = lpWvf->iHeight;
			if(lpVw->hBmpOrig != NULL)
			{
				DeleteObject(lpVw->hBmpOrig);
				DeleteDC(lpVw->hdcOrig);
			}
			hdc = GetDC(hwnd);
			lpVw->hBmpOrig = CreateCompatibleBitmap(hdc, lpVw->iOrigW, lpVw->iOrigH);
			lpVw->hdcOrig  = CreateCompatibleDC(hdc);
			SelectObject(lpVw->hdcOrig, lpVw->hBmpOrig);
			ReleaseDC(hwnd, hdc);

			
			pPos = (INT_PTR)(lpWvf->lpFrame);
			
			for(iY = 0; iY < lpVw->iOrigH; iY ++)
				for(iX = 0; iX < lpVw->iOrigW; iX ++)
				{
					SetPixel(lpVw->hdcOrig, iX, iY, ((*((LPCOLORREF)(pPos))) >> 24) | ((*((LPCOLORREF)(pPos+1))) >> 16) | ((*((LPCOLORREF)(pPos+2))) >> 8));
					pPos += 3;
				}
			InvalidateRect(hwnd, NULL, FALSE);
		}
		break;
		
	case WM_PAINT:
		{
			PAINTSTRUCT ps;
			LPVIDEOWND	lpVw = (LPVIDEOWND)GetWindowLongPtr(hwnd, GWLP_USERDATA);
			HDC hdc;	
			RECT	rc;
			
			hdc = BeginPaint(hwnd, &ps);
			if(lpVw->hdcOrig == NULL)
			{
				EndPaint(hwnd, &ps);
				return 0;
			}
			GetClientRect(hwnd, &rc);
			SetStretchBltMode(hdc, HALFTONE);
			StretchBlt(hdc, 0, 0, rc.right, rc.bottom, lpVw->hdcOrig, 0, 0, lpVw->iOrigW, lpVw->iOrigH, SRCCOPY);
			/*
			BitBlt(hdc, ps.rcPaint.left, ps.rcPaint.top, 
				ps.rcPaint.right - ps.rcPaint.left, ps.rcPaint.bottom - ps.rcPaint.top,
				lpVw->hdcOrig, ps.rcPaint.left, ps.rcPaint.top, SRCCOPY);	*/			
			EndPaint(hwnd, &ps);
		}
		break;
	case WM_ERASEBKGND:
		return 0;

	case WM_DESTROY:
		HeapFree(g_hProcHeap, 0, (LPVOID)GetWindowLongPtr(hwnd, GWLP_USERDATA));
		break;
	default:
		return DefWindowProc(hwnd, uMsg, wParam, lParam);
	}
	return 0;
}