#include "FLClues.h"

#include "WimpLib:Desktop.h"
#include "WimpLib:Display.h"
#include "WimpLib:Exception.h"
#include "WimpLib:Window.h"
#include "WimpLib:Task.h"
#include "WimpLib:Template.h"

/*-------------------------------------------------------------------------*
 *--- WListCore callbacks -------------------------------------------------*
 *-------------------------------------------------------------------------*/

#define FLItem_Width 40
#define FLItem_Height 40

static void FLClue_Plot(const void* pObject, const void* pOwner, const WPlotItem* pItem)
{
	const CSpriteHdr* pSprite = pObject;
	CRect       box;
	CPoint      pt;
	int         bg;

	IGNORE(pOwner);

	switch (pItem->m_flags & (EWItem_Active | EWItem_Selected))
	{
		case EWItem_Active:
		case EWItem_Selected:
		case (EWItem_Active + EWItem_Selected):
		{
			bg = 7;
		}
		break;
		default:
		{
			bg = 0;
		}
	}

	Desktop_SetStdColour(bg);
	box = RectToScreen(&pItem->m_box, &pItem->m_cvtinfo);
	RoundRectForPlot(&box);
	Display_RectangleFill(&box);

	/* Plot marks */
	if (pSprite)
	{
		pt.x = box.x0 +  4;
		pt.y = box.y0 +  4;
		Desktop_PlotSprite(pSprite, pt, NULL);
	}
}

static void FLClue_GetSizes(const void* pObject, const void* pOwner, int* pSizes)
{
	IGNORE(pObject);
	IGNORE(pOwner);
	IGNORE(pSizes);
}

static CSize FLClue_GetBox(const void* pObject, const void* pOwner, const int* pSizes, const int* pMaxSizes)
{
	CSize size;

	IGNORE(pObject);
	IGNORE(pOwner);
	IGNORE(pSizes);
	IGNORE(pMaxSizes);

	size.cx = FLItem_Width;
	size.cy = FLItem_Height;

	return size;
}

static WListCore_FWList FLClues_FWList =
{
	  {
		  FLClue_Plot
		, FLClue_GetSizes
		, FLClue_GetBox
		, NULL
	  }
	, WOwner_PlotBackGround_White
};

static EListenerAction FLClues_EventHandler(void* handle, const Event* e)
{
	IGNORE(handle);

	if (e->Type == EEvent_Mouse)
	{
		// Treat menu as select
		Mouse* m = (Mouse*) e->pData;

		if (m->but & EBut_Menu)
		{
			m->but |= EBut_Select;
			m->but &= ~EBut_Menu;
		}
	}

	return EListenerAction_ContinueEvent;
}

void throw_FLClues_FLClues(WList* This, const CSpriteArea* pClues)
{
	CTemplate* t = throw_Templates_Blank(0, EWind_VScroll | EWind_Pane | EWind_Moveable, 40, 200);
	CSpriteHdr* pSprite;

	throw_WList_WListEx(This, EWList_SelModePopup, t, This, &FLClues_FWList);
	throw_WList_Insert(This, -1, NULL);
	pSprite = Sprites_FirstSprite(pClues);
	for (; pSprite; pSprite = Sprites_NextSprite(pClues, pSprite))
	{
		throw_WList_Insert(This, -1, pSprite);
	}
	throw_Window_RegisterEventHandler(WList_GetWindow(This), FLClues_EventHandler, This, true);
}

void FLClues_NotFLClues(WList* This)
{
	Window_DeRegisterEventHandler(WList_GetWindow(This), FLClues_EventHandler, This);
	WList_NotWList(This);
}
