#include "WebControl.h"
#include "SysMsg.h"

const char WebControl::_className[32] = WEB_CTRL_CLASS_NAME;
int WebControl::_nbWindow = 0;

void WebControl::init(HINSTANCE hInst, HWND hWnd)
{
	Window::init(hInst, hWnd);
	
	WNDCLASSEX		wc;

	// Register the class of our window to host the browser. 'WindowProc' is our message handler
	// and 'ClassName' is the class name. You can choose any class name you want.
    ::ZeroMemory(&wc, sizeof(WNDCLASSEX));
	wc.cbSize = sizeof(WNDCLASSEX);
	wc.hInstance = _hInst;
	wc.lpfnWndProc = WebCtrl_Proc;
	wc.lpszClassName = _className;
	
    if (!::RegisterClassEx(&wc))
	{
		systemMessage("System Err");
		throw int(666);
	}
	
    _hSelf = ::CreateWindowEx(0,\
						 _className,\
						 "Notepad++ Visionner",\
						 WS_OVERLAPPED,\
						 CW_USEDEFAULT, 0,\
						 CW_USEDEFAULT, 0,\
						 NULL,\
						 NULL,\
						 _hInst,\
						 (LPVOID)this);
	if (!_hSelf)
	{
		systemMessage("System Err");
		throw int(888);
	}
}

LRESULT CALLBACK WebControl::WebCtrl_Proc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
  switch(Message)
  {
	case WM_NCCREATE : // First message we get the ptr of instantiated object
                       // then stock it into GWL_USERDATA index in order to retrieve afterward
	{
		WebControl *pWebControl = (WebControl *)(((LPCREATESTRUCT)lParam)->lpCreateParams);
		pWebControl->_hSelf = hwnd;
		::SetWindowLong(hwnd, GWL_USERDATA, (LONG)pWebControl);

		return TRUE;
	}

    default :
    {
      return ((WebControl *)::GetWindowLong(hwnd, GWL_USERDATA))->runProc(hwnd, Message, wParam, lParam);
    }
  }
}

LRESULT WebControl::runProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch (uMsg)
	{
		case WM_SIZE:
		{
			// Resize the browser object to fit the window
			ResizeBrowser(hwnd, LOWORD(lParam), HIWORD(lParam));
			return(0);
		}

		case WM_CREATE:
		{
			if (EmbedBrowserObject(hwnd)) return(-1);

			// Another window created with an embedded browser object
			++_nbWindow;

			// Success
			return(0);
		}

		case WM_DESTROY:
		{
			// Detach the browser object from this window, and free resources.
			UnEmbedBrowserObject(hwnd);

			--_nbWindow;

			//if (!_nbWindow) PostQuitMessage(0);

			return(TRUE);
		}


	}

	return (::DefWindowProc(hwnd, uMsg, wParam, lParam));
}