#include "stdafx.h"
#include "../../../include/com_server.h"
#include "led.h"

DEFINE_GUID(CLSID_LED, 0x681299e1, 0x8bb4, 0x11d3, 0xad, 0xaa, 0x00,0x60,0x67,0x49,0x62,0x45);

LEDWin::LEDWin(ImpComponent* pcomp, BoolConnection& pin):
		coc(pin, this, &LEDWin::pinChanged),
		pComp(pcomp),
		pPopupMenu(new CMenu) {
	pPopupMenu->CreatePopupMenu();
	pPopupMenu->AppendMenu(MF_STRING, 10, "&Connect...");
	pPopupMenu->AppendMenu(MF_STRING, 20, "&Toggle Led");
	hIconOn=::LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_ICON1));
	hIconOff=::LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_ICON2));
	bitmapOn.Attach(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_BITMAP1)));
	bitmapOff.Attach(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_BITMAP2)));
	pComp->SetCompWinIcon(coc->get() ? hIconOn : hIconOff);
	pComp->SetCompWinTitle(coc->get() ? "Led is ON" : "Led is OFF");
}

LEDWin::~LEDWin() {
	delete pPopupMenu;
}


BEGIN_MESSAGE_MAP(LEDWin, CWnd)
	//{{AFX_MSG_MAP(LEDWin)
	ON_WM_PAINT()
	ON_WM_CONTEXTMENU()
	ON_WM_SIZE()
	ON_COMMAND(10, CmConnect)
	ON_COMMAND(20, CmToggle)
	ON_WM_CHAR()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()


void LEDWin::OnPaint() {
	CPaintDC dc(this);
	CDC memDC;
    memDC.CreateCompatibleDC(&dc);


	BITMAP bm;
	if (coc->get()) {
		bitmapOn.GetBitmap(&bm);
		memDC.SelectObject(&bitmapOn);
	}
	else {
		bitmapOff.GetBitmap(&bm);
		memDC.SelectObject(&bitmapOff);
	}

	RECT rect;
	GetClientRect(&rect);

	dc.StretchBlt(0, 0, rect.right, rect.bottom, &memDC, 0 , 0, bm.bmWidth, bm.bmHeight, SRCCOPY);
}

void LEDWin::OnSize(UINT nType, int cx, int cy) {
	CWnd::OnSize(nType, cx, cy);
	Invalidate(true);
}

void LEDWin::pinChanged() {
	pComp->SetCompWinIcon(coc->get() ? hIconOn : hIconOff);
	pComp->SetCompWinTitle(coc->get() ? "Led is ON" : "Led is OFF");
	Invalidate(false);
}

void LEDWin::CmToggle() {
	coc->set(!coc->get());
}

void LEDWin::CmConnect() {
	pComp->ConnectDialog();
}

void LEDWin::OnContextMenu(CWnd* pWnd, CPoint point) {
	pPopupMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this);
}


LED::LED(): LEDWindow(0) {
	SetComponentName("Led");
	SetGroupName("CDK Visual C++ 6.0 Examples");
	Expose(pin, "Led input");
}

HWND LED::CreateComponentWindow(HWND parent) {
	if (LEDWindow==0) {
		LEDWindow = new LEDWin(this, pin);
		// This LEDWin will be deleted by its parent. So don't call delete yourself!
		RECT r={0, 0, 104, 104};
		LEDWindow->Create(0,"",WS_CHILD|WS_VISIBLE, r, LEDWindow->FromHandle(parent), 0);
	}
	return LEDWindow->m_hWnd;
}


void RegisterClassFactories() {
	ClassFactory* new_classfactory=new ComponentFactory<LED>(CLSID_LED);
	class_factories.push_back(new_classfactory);
}

void LEDWin::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) {
	switch (nChar) {
		case VK_SPACE:
			CmToggle();
			break;
	}
	CWnd::OnChar(nChar, nRepCnt, nFlags);
}
