#include "w_imglst.hpp"

#if defined(ZAF_WIN32)
ZafTreeImageList::ZafTreeImageList(ZafDisplay *_display, HWND _treeHandle) :
	display(_display), treeHandle(_treeHandle)
{
	images = 0;
	maxImages = images + 10;
	handle = ImageList_Create(16, 16, ILC_COLOR8, images, maxImages - images);
}

ZafTreeImageList::~ZafTreeImageList(void)
{
	ImageList_Destroy(handle);
}

int ZafTreeImageList::AddImage(ZafBitmapData *bitmapData)
{
	ZafTreeImageItem *item = (ZafTreeImageItem *)First();
	while(item)
	{
		if (item->bitmapData == bitmapData)
		{
			item->count++;
			return item->index;
		}

		item = (ZafTreeImageItem *)item->Next();
	}

	// No matching images were found.
//???
	if (!bitmapData->handle)
		display->ConvertToOSBitmap(*bitmapData);
	int index = ImageList_Add(handle, bitmapData->handle, bitmapData->mask);
//???
//	display->DestroyOSBitmap(*bitmapData);
	images++;
	item = new ZafTreeImageItem(bitmapData, index);
	Add(item);
	return index;
}

void ZafTreeImageList::SubtractImage(ZafBitmapData *bitmapData)
{
	ZafTreeImageItem *item;
	for (ZafElement *element = First(); element; element = element->Next())
	{
		item = (ZafTreeImageItem *)element;
		if (item->bitmapData == bitmapData)
			item->count--;

		if (item->count == 0)
		{
			ImageList_Remove(handle, item->index);
			Subtract(item);
			delete item;
			images--;
		}
	}
}


ZafTreeImageItem::ZafTreeImageItem(ZafBitmapData *_bitmapData, int _index) :
	bitmapData(_bitmapData), index(_index)
{
}

ZafTreeImageItem::~ZafTreeImageItem(void)
{
}

#endif
