#include "global.h"
#include "cinfowin.h"
#include "resource.h"

void CInfoWindow::SetText(char *title)
{
	if (text) {_DELETE(text); text = NULL;}
	text = _NEW(char[strlen(title)+1]);
	strcpy(text, title);
	::ShowWindow(hwnd, SW_SHOWNORMAL);
	::RedrawWindow(hwnd, NULL, NULL, RDW_ERASE|RDW_INVALIDATE|RDW_UPDATENOW);
//	wmPaint();
}

void CInfoWindow::wmPaint()
{
	HDC hwndDc = ::GetDC(hwnd);
	HDC dc = ::CreateCompatibleDC(hwndDc);
	::SelectObject(dc, hBmp);
	::BitBlt(hwndDc, 5, 10, 30, 10, dc, step*30, 0, SRCCOPY);
	::BitBlt(hwndDc, 300-5-30, 10, 30, 10, dc, ((step+1)%3)*30, 0, SRCCOPY);
	RECT rc; rc.left = 40; rc.top = 0; rc.right = 300-40; rc.bottom = 30;
	FillRect(hwndDc, &rc, hBrush);
	::SetBkMode(hwndDc, TRANSPARENT);
	::SelectObject(hwndDc, hFont);
	::DrawText(hwndDc, text, -1, &rc, DT_CENTER|DT_VCENTER|DT_SINGLELINE);
	::ReleaseDC(hwnd, hwndDc);
	::DeleteDC(dc);
}

LRESULT CALLBACK CInfoWindow::WindowProc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp)
{
	switch (msg)
	{
	case WM_PAINT:
		::DefWindowProc(hwnd, msg, wp, lp);
		wmPaint();
		return 0;
	case WM_TIMER:
		if (wp == 1234)
			NextStep();
		break;

	}
	return ::DefWindowProc(hwnd,msg,wp,lp);
}

void CInfoWindow::NextStep()
{
	step++;
	if (step == 3) step = 0;
	wmPaint();
}

LRESULT CALLBACK CInfoWindow::StaticWindowProc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp)
{
	DWORD p = ::GetWindowLong(hwnd,GWL_USERDATA);
	return ((CInfoWindow*)p)->WindowProc(hwnd,msg,wp,lp);
}

CInfoWindow::~CInfoWindow()
{
	if (text) {_DELETE(text);}
	::KillTimer(hwnd, 1234);
	::DeleteObject(hFont);
	::DeleteObject(hBmp);
	::DestroyWindow(hwnd);
}

void CInfoWindow::StopAnimation()
{
	::KillTimer(hwnd, 1234);
}

void CInfoWindow::Animate()
{
	//automaticke prekreslovanie pomocou timera
	::SetTimer(hwnd, 1234, 200, NULL);
}

CInfoWindow::CInfoWindow()
{
	static char classname[] = "cinfowindowinlog";
	WNDCLASS wc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	hBrush = ::CreateSolidBrush(0xf0f0f0);
	wc.hbrBackground = hBrush;
	wc.hCursor = ::LoadCursor(0, IDC_WAIT);
	wc.hIcon = 0;
	wc.hInstance = app.hInstance;
	wc.lpfnWndProc = (WNDPROC)StaticWindowProc;
	wc.lpszClassName = classname;
	wc.lpszMenuName = 0;
	wc.style = CS_SAVEBITS;
	::RegisterClass(&wc);

	RECT rc; ::GetWindowRect(app.mainWindow->GetHandle(), &rc);
	hwnd = ::CreateWindowEx(0, classname, NULL, WS_POPUP|WS_BORDER,
		(rc.left + rc.right)/2 - 150, (rc.top + rc.bottom)/2-15, 300, 30, app.mainWindow->GetHandle(), 0, 
		app.hInstance, 0);

	//asociuj okno s jeho instanciou
	::SetWindowLong(hwnd,GWL_USERDATA,(DWORD)this);

	hBmp = ::LoadBitmap(app.hInstance, MAKEINTRESOURCE(BMP_WAITING));
	step = 0;//faza animacie
	text = NULL;
	animThread = NULL;

	HDC hdc = GetDC(NULL);
    DWORD lfHeight = -MulDiv(9, GetDeviceCaps(hdc, LOGPIXELSY), 72);
    ReleaseDC(NULL, hdc);
	hFont = (HFONT)::CreateFont(lfHeight, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
		OUT_CHARACTER_PRECIS, CLIP_CHARACTER_PRECIS,
		DEFAULT_QUALITY, 0, "Microsoft Sans Serif");

}