#include "global.h"
#include "chtml.h"
#include "resource.h"
#include "cwebpage.h"


CHtml::CHtml(HWND parent)
{
	tmp = NULL;

	HMODULE h = ::LoadLibrary("user32.dll");
	_SetLayeredWindowAttributes = (SETLAYERED) ::GetProcAddress(h, "SetLayeredWindowAttributes");
	::FreeLibrary(h);

	char classname[] = "chtmlinlogwindow";
	WNDCLASS wc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 40;
	wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1);
	wc.hCursor = ::LoadCursor(0,IDC_ARROW);
	wc.hIcon = NULL;
	wc.hInstance = app.hInstance;
	wc.lpfnWndProc = (WNDPROC)CHtml::StaticWindowProc;
	wc.lpszClassName = classname;
	wc.lpszMenuName = 0;
	wc.style = 0;
	::RegisterClass(&wc);

	canBeLayered = ((LOBYTE(LOWORD(GetVersion()))) >=5);

	RECT rcP;
	::GetWindowRect(app.mainWindow->GetHandle(), &rcP);

	if (canBeLayered)
	{
		hwnd = ::CreateWindowEx(WS_EX_LAYERED, classname, NULL, WS_OVERLAPPED|WS_THICKFRAME|WS_SYSMENU ,
			rcP.right-300, rcP.top+30, 300, 400, parent, NULL, app.hInstance, 0);
	}
	else
	{
		hwnd = ::CreateWindowEx(0, classname, NULL, WS_OVERLAPPED|WS_THICKFRAME|WS_SYSMENU ,
			rcP.right-300, rcP.top+30, 300, 400, parent, NULL, app.hInstance, 0);
	}

	::SetWindowLong(hwnd, 0, (DWORD)this);
	::EmbedBrowserObject(hwnd);
	GetWindowLong(hwnd, GWL_USERDATA);
}

CHtml::~CHtml()
{
	if (tmp)
	{
		_DELETE(tmp);
	}

	if (hwnd)
		DestroyWindow(hwnd);
}

void CHtml::ViewHTML(char *title, char *content)
{
	if (tmp)
	{
		_DELETE(tmp);
	}

	DWORD len = strlen(content)+1;
	tmp = _NEW(char[len]);
	::CopyMemory(tmp, content, len);

	::UnEmbedBrowserObject(hwnd); ::EmbedBrowserObject(hwnd);
	::DisplayHTMLStr(hwnd, tmp);
	::SetWindowText(hwnd, title);

	if (_SetLayeredWindowAttributes)
		_SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA);

	::ShowWindow(hwnd, SW_SHOW);
}

HWND CHtml::GetHandle()
{
	return hwnd;
}

LRESULT CALLBACK  CHtml::StaticWindowProc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp)
{
	DWORD p = ::GetWindowLong(hwnd,0);
	if (p)
		return ((CHtml*)p)->WindowProc(hwnd,msg,wp,lp);
	else
		return ::DefWindowProc(hwnd, msg, wp, lp);
}

LRESULT CALLBACK CHtml::WindowProc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp)
{
	switch (msg)
	{
	case WM_ACTIVATE:
		if (_SetLayeredWindowAttributes)
		{
			if (wp != WA_INACTIVE)
				//okno sa aktivuje
				_SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA);
			else
				//okno sa deaktivuje
				_SetLayeredWindowAttributes(hwnd, 0, 100, LWA_ALPHA);
		}
		break;
	case WM_SIZE:
		{
			if (tmp)
			{
				//resize okna v cwebpage zdrojakoch nefunguje, neviem preco
				//jedina moznost to je spravit takto
				//zrusi to a nanovo to cele vytvorit
				::UnEmbedBrowserObject(hwnd); ::EmbedBrowserObject(hwnd);
				::DisplayHTMLStr(hwnd, tmp);
			}
		}
		break;
	case WM_CLOSE:
		//nie zavriet, ale skryt
		::ShowWindow(hwnd, SW_HIDE);
		return 0;
	case WM_DESTROY:
		::UnEmbedBrowserObject(hwnd);
		this->hwnd = NULL;
		break;
	}
	return ::DefWindowProc(hwnd, msg, wp, lp);
}


SETLAYERED CHtml::_SetLayeredWindowAttributes = NULL;