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

QMiniBlink::QMiniBlink(QWidget *parent)
	: QWidget(parent){
	
	this->parent = parent;
	wkeView = nullptr;
	//QSizePolicy sizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::QSizePolicy::Expanding);
	//setSizePolicy(sizePolicy);
}
void QMiniBlink::init() {
	ui.setupUi(this);
	wkeInit();
	RECT rect;
	GetWindowRect((HWND)parent->winId(), &rect);
	resize(rect.right - rect.left, rect.bottom - rect.top);
	this->wkeView = wkeCreateWebWindow(WKE_WINDOW_TYPE_CONTROL, (HWND)this->winId(), 0, 0, rect.right - rect.left, rect.bottom - rect.top);

	wkeSetNavigationToNewWindowEnable(this->wkeView, false);
	wkeShowWindow(this->wkeView, TRUE);
	SetParent(wkeGetWindowHandle(this->wkeView), (HWND)this->winId());
	wkeMoveWindow(this->wkeView, 0, 0, rect.right - rect.left, rect.bottom - rect.top);
	//while(this->firstUrl.isEmpty()){}
	//wkeLoadURL(this->wkeView, this->firstUrl.toStdString().c_str());
	SetWindowSubclass((HWND)this->winId(), subClassProc, 0, (DWORD_PTR)this);
	//wkeRunMessageLoop();
}
QMiniBlink::~QMiniBlink(){
	qDebug() << "Destroyed";
}
void QMiniBlink::ondestroy() {
	if (this->wkeView != nullptr) {
		wkeDestroyWebView(wkeView);
		qDebug() << "Destroyed";
	}
	wkeShutdown();
}
void QMiniBlink::switchUrl(QString url) {
	wkeLoadURL(wkeView, 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);
	wkeMoveWindow(wkeView, 0, 0, rect.right - rect.left, rect.bottom - rect.top);

}
