#include <zaf.hpp>

class BandingWindow : public ZafWindow
{
public:
	BandingWindow(void);
	virtual ZafEventType Draw(const ZafEventStruct &event, ZafEventType ccode);
	virtual ZafEventType Event(const ZafEventStruct &event);

	void RubberBand(ZafPositionStruct downClickPosition);

protected:
	ZafPositionStruct origin;
	ZafPositionStruct lastPosition;
};

BandingWindow::BandingWindow(void) :
	ZafWindow(0, 0, 40, 10)
{
	SetRegionType(ZAF_AVAILABLE_REGION);
	SetOSDraw(false);
}

ZafEventType BandingWindow::Draw(const ZafEventStruct &, ZafEventType ccode)
{
	ZafRegionStruct drawRegion = BeginDraw();

	display->SetBackground(ZAF_CLR_BLACK);
	display->Rectangle(drawRegion, 0, true);

	EndDraw();

	return (ccode);
}

ZafEventType BandingWindow::Event(const ZafEventStruct &event)
{
	ZafEventType ccode = LogicalEvent(event);

	switch (ccode)
	{
	case S_REGISTER_OBJECT:
		ccode = ZafWindow::Event(event);
		RegisterMouse(true, true, true);
		break;

	case L_BEGIN_SELECT:
		{
		ccode = ZafWindow::Event(event);

		windowManager->SetMouseEventRoute(this);
		origin = event.position;
		lastPosition.column = -1000;
		}
		break;

	case L_CONTINUE_SELECT:
		{
		ccode = ZafWindow::Event(event);

		int left = origin.column;
		int top = origin.line;
		int right = lastPosition.column;
		int bottom = lastPosition.line;

		BeginDraw();
		Display()->SetMode(ZAF_MODE_XOR);
		Display()->SetForeground(ZAF_CLR_WHITE);

		if (lastPosition.column != -1000)
		{
			Display()->Line(left, top, right, top);
			Display()->Line(right, top, right, bottom);
			Display()->Line(left, bottom, right, bottom);
			Display()->Line(left, top, left, bottom);
		}

		right = event.position.column;
		bottom = event.position.line;

		Display()->Line(left, top, right, top);
		Display()->Line(right, top, right, bottom);
		Display()->Line(left, bottom, right, bottom);
		Display()->Line(left, top, left, bottom);
		Display()->SetMode(ZAF_MODE_COPY);
		EndDraw();

		lastPosition = event.position;
		}
		break;

	case L_END_SELECT:
		windowManager->SetMouseEventRoute(ZAF_NULLP(ZafWindowObject));
		break;

	default:
		ccode = ZafWindow::Event(event);
	}

	return (ccode);
}

int ZafApplication::Main()
{
	// Ensure main() is linked properly.
	LinkMain();

	ZafWindow *mainWin = new ZafWindow(0, 0, 40, 10);
	mainWin->AddGenericObjects(ZAF_ITEXT("Banding Test"));
	mainWin->Add(new BandingWindow());

	zafWindowManager->Add(mainWin);

	Control();

	return (0);
}
