#include "stdafx.h"
#include "Painter.h"
#include "App.h"
#include "Surface.h"
#include "Exception.h"

namespace gui {

	Painter::Painter() : graphics(null) {
		bgColor = gui::app(engine())->defaultBgColor;
	}

	Painter::~Painter() {
		detach();
	}

	void Painter::onAttach(Surface *surface) {
		if (Surface2D *s = as<Surface2D>(surface)) {
			graphics = s->createGraphics(engine());
		} else {
			throw new (this) InternalError(S("We expect a 2D surface for 2D painters!"));
		}
	}

	void Painter::onDestroy() {
		if (graphics) {
			graphics->surfaceDestroyed();
			graphics->destroy();
		}
		graphics = null;
	}

	void Painter::onResize() {
		if (graphics)
			graphics->surfaceResized();
	}

	Bool Painter::render(Size size, Graphics *graphics) {
		return false;
	}

	Image *Painter::captureImage(Size size, Color bgColor) {
		return captureImage(size, &captureImageFn, &bgColor);
	}

	Bool Painter::captureImageFn(BasicPainter *p, Surface *surface, void *data) {
		Painter *me = (Painter *)p;
		Color *bgColor = (Color *)data;

		try {
			me->graphics->beforeRender(*bgColor);
			me->render(surface->size / surface->scale, me->graphics);
			return me->graphics->afterRender();
		} catch (...) {
			me->graphics->afterRender();
			throw;
		}
	}

	void Painter::render(Surface *surface, Bool &more, Bool &ok) {
		try {
			graphics->beforeRender(bgColor);
			more = render(surface->size / surface->scale, graphics);
			ok = graphics->afterRender();
		} catch (...) {
			ok = graphics->afterRender();
			throw;
		}
	}

}
