#include "qminiblink.h"
#include <QThread>
#include <QDebug>
#pragma comment (lib,"Comctl32.lib")

QMiniBlink::QMiniBlink(QWidget *parent)
	: QWidget(parent){
	
	this->parent = parent;
	//QSizePolicy sizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::QSizePolicy::Expanding);
	//setSizePolicy(sizePolicy);
}
void QMiniBlink::init() {
	ui.setupUi(this);
	mbSettings settings;
	memset(&settings, 0, sizeof(mbSettings));
	mbInit(&settings);
	RECT rect;
	GetWindowRect((HWND)parent->winId(), &rect);
	resize(rect.right - rect.left, rect.bottom - rect.top);
	this->mbView = mbCreateWebWindow(MB_WINDOW_TYPE_CONTROL, (HWND)this->winId(), 0, 0, rect.right - rect.left, rect.bottom - rect.top);

	mbSetNavigationToNewWindowEnable(this->mbView, false);
	mbShowWindow(this->mbView, TRUE);
	SetParent(mbGetHostHWND(this->mbView), (HWND)this->winId());
	mbMoveWindow(this->mbView, 0, 0, rect.right - rect.left, rect.bottom - rect.top);
	//while(this->firstUrl.isEmpty()){}
	//mbLoadURL(this->mbView, this->firstUrl.toStdString().c_str());
	SetWindowSubclass((HWND)this->winId(), subClassProc, 0, (DWORD_PTR)this);
	//mbRunMessageLoop();
}
QMiniBlink::~QMiniBlink(){
	qDebug() << "Destroyed";
}
void QMiniBlink::ondestroy() {
	mbDestroyWebView(mbView);
	qDebug() << "Destroyed";
	mbUninit();
}
void QMiniBlink::switchUrl(QString url) {
	mbLoadURL(mbView, url.toStdString().c_str());
}
LRESULT CALLBACK QMiniBlink::subClassProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
	QMiniBlink *obj = (QMiniBlink *)dwRefData;
	if (obj == nullptr)
		return DefSubclassProc(hWnd, uMsg, wParam, lParam);
	switch (uMsg) {
	case WM_SIZE:
		obj->autojustWebViewSize();
		break;
	default:
		break;
	}
	return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
void QMiniBlink::autojustWebViewSize()
{
	RECT rect;
	GetWindowRect((HWND)this->winId(), &rect);
	mbMoveWindow(mbView, 0, 0, rect.right - rect.left, rect.bottom - rect.top);

}
