#include "stdafx.h"
#include "Group.h"
#include "App.h"
#include "Utils/Bitwise.h"

namespace gui {

	Group::Group() {}

	Group::Group(Str *title) {
		text(title);
	}

#ifdef GUI_WIN32

	// Note: Will be scaled based on display scale factor.
	static const Int hBorder = 2;
	static const Int vBorder = 3;

	bool Group::create(ContainerBase *parent, nat id) {
		// Create the group box. Subclass it so that we can erase our background as needed.
		// Note: We need the cWin32Subclass so that we can handle WM_ERASEBKGND in the parent class.
		bool ok = createEx(WC_BUTTON,
						childFlags | BS_GROUPBOX | WS_CLIPCHILDREN,
						WS_EX_CONTROLPARENT,
						parent->handle().hwnd(), 0, cWin32Subclass);
		if (!ok)
			return false;

		updateChildPos();

		return true;
	}

	void Group::text(Str *text) {
		SingleChildContainer::text(MnemonicStr(text).win32Mnemonic());

		if (text->empty()) {
			textHeight = Float(vBorder);
		} else {
			textHeight = font()->stringSize(text).h;
		}
	}

	Size Group::minSize() {
		Size childMinSize;
		if (Window *child = content())
			childMinSize = child->minSize();

		return childMinSize + Size(Float(hBorder * 2), Float(vBorder + textHeight));
	}

	void Group::resized(Size size) {
		SingleChildContainer::resized(size);

		updateChildPos();
	}

	void Group::updateChildPos() {
		Window *child = content();
		if (!child)
			return;

		if (!created())
			return;

		child->pos(Rect(
					Point(Float(hBorder), textHeight),
					pos().size() - Size(Float(hBorder * 2), Float(vBorder) + textHeight)));
	}


#endif
#ifdef GUI_GTK

	bool Group::create(ContainerBase *parent, nat id) {
		const gchar *label = NULL;
		Str *text = this->text();
		if (text->any())
			label = text->utf8_str();

		initWidget(parent, gtk_frame_new(label));
		return true;
	}

	void Group::text(Str *text) {
		SingleChildContainer::text(text);

		if (created()) {
			const gchar *label = NULL;
			if (text->any())
				label = text->utf8_str();

			gtk_frame_set_label(GTK_FRAME(handle().widget()), label);
		}
	}

	Size Group::minSize() {
		gint w = 0, h = 0;

		if (created()) {
			if (Window *c = content())
				c->updateGtkMinSize();

			gtk_widget_get_preferred_width(handle().widget(), &w, NULL);
			gtk_widget_get_preferred_height(handle().widget(), &h, NULL);
		}

		return Size(Float(w), Float(h));
	}

	void Group::resized(Size size) {
		SingleChildContainer::resized(size);
	}

#endif

}
