#define SCREENCOUNT 3

class memwindow : public actualwindow
{
	int			_cur;
	struct PIXIMAGE
	{
		int			width;
		int			height;
		char *		pixrect;
		string		action;
		void operator=(PIXIMAGE &copy)
		{
			assert( &copy!=this );
			width = copy.width;
			height= copy.height;
			pixrect = copy.pixrect;
			action = copy.action;
		};
		PIXIMAGE():pixrect(0){};
		PIXIMAGE(int w,int h,char *ppix,string &s):width(w),height(h),pixrect(ppix),action(s){};
		~PIXIMAGE(){};
	};
	PIXIMAGE		_pscreen[SCREENCOUNT];
	
public:
	memwindow();
	~memwindow();
	virtual void draw();
	void grabscreen(int,int,string &);
	void prev();
	void next();
	void current();
	void clearscreens();
};

memwindow::memwindow():actualwindow("B+tree visualization"),_cur(0)
{
}

memwindow::~memwindow()
{
	for (int i=0;i<SCREENCOUNT;i++)
	{
		if (_pscreen[i].pixrect)
			del_pixrect( _pscreen[i].pixrect );
	}
}

void memwindow::clearscreens()
{
	for (int i=0;i<SCREENCOUNT;i++)
	{
		if (_pscreen[i].pixrect)
		{
			del_pixrect( _pscreen[i].pixrect );
			_pscreen[i].pixrect = 0;
			_pscreen[i].action = "";
		}
	}
	_cur = 0;
}

void memwindow::draw()
{
	init(0,width(),0);
	clear();
	string s("The image shown displays ");
	if ( !_cur )
		s+="the most recent action";
	else
		s+=string("%d actions before the last action",_cur);

	draw_ctext((xmax()-xmin())/2 , ymax()-10 , s , _cur?red:black );
	draw_ctext((xmax()-xmin())/2 , ymax()-30 , string("Action happend : ")+_pscreen[_cur].action , blue );
	
	if ( _cur>0 )
		draw_ctext((xmax()-xmin())/2 , ymax()-50 , string("Next action : ")+_pscreen[_cur-1].action , blue );

	if ( !_pscreen[_cur].pixrect )
		return;

	int imgwidth = _pscreen[_cur].width;
	int imgheight = _pscreen[_cur].height;
	int x = (xmax()-xmin()-imgwidth)/2;
	int y = imgheight-get_height(_pscreen[_cur].pixrect);
	set_clip_rectangle(x,60,x+imgwidth,imgheight-50);
	put_pixrect(x,y+30,_pscreen[_cur].pixrect);
	reset_clipping();
}

void memwindow::grabscreen(int width,int height,string &s)
{
	//delete the prev picrect ...
	if ( _pscreen[SCREENCOUNT-1].pixrect )
		del_pixrect( _pscreen[SCREENCOUNT-1].pixrect );

	for (int i=SCREENCOUNT-1;i>0;i--)
		_pscreen[i] = _pscreen[i-1];

	char * ppix;
	stop_buffering( ppix );
	_pscreen[0] = PIXIMAGE(width,height,ppix,s);
	_cur = 0;

	redraw();
}

void memwindow::prev()
{
	if ( _cur<SCREENCOUNT-1 )
		++_cur;
	redraw();
}

void memwindow::next()
{
	if ( _cur>0 )
		--_cur;
	redraw();
}

void memwindow::current()
{
	_cur = 0;
	redraw();
}
