////////////////////////////////////////////////////////////////////////////////
// GLContextMenu.cpp
// Copyright Björn Ganster
// Developed since 2005
////////////////////////////////////////////////////////////////////////////////

#include "Font.h"
#include "GLContextMenu.h"
#include "Texture.h"

#define FILE_NUMBER FILE_NO_GLCONTEXTMENU_CPP

////////////////////////////////////////////////////////////////////////////////
// Constructor

GLContextMenu::GLContextMenu (GLWindow* _parent, int left, int top)
: GLWindow ("GLContextMenu", GLContextMenu_ID, _parent, left, top)
{
	backgroundColor = Color (0.7f, 0.7f, 0.7f);
}

// Destructor
GLContextMenu::~GLContextMenu()
{
}

// Add an entry, name and texture should persist until menu deletion
bool GLContextMenu::addMenuItem (const BGCPString& name, MessageListener* listener, int ID)
{
	SET_SCOPE;
	GLContextMenuEntry newEntry;
	newEntry.name = name;
	newEntry.listener = listener;
	newEntry.ID = ID;
	entries.push_back (newEntry);

	Font* font = getDefaultFont();
	height = font->getCharHeight() * (int) entries.size()+3;
	int textWidth = font->textWidth(name);
	width = std::max(width, textWidth);
	int entryWidth = 10 * name.getCharCount();
	if (entryWidth > width)
		width = entryWidth;

	RETURN true;
}

////////////////////////////////////////////////////////////////////////////////
// Events

void GLContextMenu::keypressed (BGKey /*key*/, bool /*shiftHeld*/, bool /*ctrlHeld*/, bool /*down*/, bool /*repeat*/)
{
}

GLWindow* GLContextMenu::buttonStateChanged (int button, bool down, int x, int y)
{
	if (left <= x
		&&  x < left + width
		&&  top <= y
		&&  y < top + height
		&&  button == 1
		&&  !down) 
	{
		Font* font = getDefaultFont();
		int num = std::min ((y-top) / font->getCharHeight(), (int) entries.size()-1);
		if (entries[num].listener != NULL)
			entries[num].listener->receiveMessage (&entries[num], ContextMenuClickEvent);
		delete this;
		return NULL;
	}
	return this;
}

void GLContextMenu::mouseMoved (int /*x*/, int /*y*/)
{
}

////////////////////////////////////////////////////////////////////////////////
// Render

void GLContextMenu::render(int x, int y, int w, int h)
{
   GLWindow::prepareToRender(x, y, w, h);
   glTranslated (-1.0, 1.0, 0.0);
   glScaled (2/((double) getWidth()), -2/((double) getHeight()), 1.0);   // Render rule graph nodes
   glEnable (GL_TEXTURE_2D);

   glDisable (GL_TEXTURE_2D);
   glDisable (GL_DEPTH_TEST);

   glColor3d (0.0, 0.0, 0.0);
   for (size_t i = 0; i < entries.size(); i++) {
      const GLContextMenuEntry& entry = entries[i];
      Font* font = getDefaultFont();
      font->renderText (entry.name, 0, (int) i*font->getCharHeight(), width);
   }
}
