#include "softosd.h"

// --- cSoftOsd -----------------------------------------------
cSoftOsd::cSoftOsd(FbRenderer *Out, int X, int Y) : cOsd(X, Y)
{
	_Out = Out;
	_X = X;
	_Y = Y;
	Imlib_Context ctx = imlib_context_new();
	imlib_context_push(ctx);
  	_OsdImage = imlib_create_image(720, 576);
    	imlib_context_set_image(_OsdImage);
  	// clear the image
	UINT8 *dataptr = (UINT8 *) imlib_image_get_data();
	memset(dataptr, 0, 720 * 576 * 4);
	imlib_image_put_back_data( (DATA32 *) dataptr);
	// nicer scaling
	imlib_context_set_anti_alias(1);
	// dither for depths < 24bpp
	imlib_context_set_dither(1);
}

cSoftOsd::~cSoftOsd()
{
	// clear the image
	imlib_context_set_image(_OsdImage);
	UINT8 *dataptr = (UINT8 *) imlib_image_get_data();
	memset(dataptr, 0, 720 * 576 * 4);
	imlib_image_put_back_data( (DATA32 *) dataptr);
	if (_Out) _Out->refresh();
	imlib_context_set_image(_OsdImage);
	imlib_free_image();
}

eOsdError cSoftOsd::CanHandleAreas(const tArea *Areas, int NumAreas)
{
eOsdError Result = cOsd::CanHandleAreas(Areas, NumAreas);

return Result;
}

void cSoftOsd::Flush(void)
{
	cBitmap *Bitmap;
       
	// clear the image
	imlib_context_set_image(_OsdImage);
	UINT8 *dataptr = (UINT8 *) imlib_image_get_data();
	memset(dataptr, 0, 720 * 576 * 4);
	imlib_image_put_back_data( (DATA32 *) dataptr);
	
	for (int i = 0; (Bitmap = GetBitmap(i)) != NULL; i++)
	{
  		const tIndex  *adr;
    		tColor        c;
		int a,r,g,b;
       
        	for (int y = 0; y < Bitmap->Height(); y++)
		{
			for (int x = 0; x < Bitmap->Width(); x++)
			{
				adr = Bitmap->Data(x, y);
				c = Bitmap->Color(*adr);
				a = (c >> 24) & 255; //Alpha
				r = (c >> 16) & 255; //Red
				g = (c >> 8) & 255;  //Green
				b = c & 255;         //Blue
				imlib_context_set_color(r, g, b, a);	
				imlib_image_draw_pixel(x + _X +  Bitmap->X0(), y + _Y +  Bitmap->Y0(), char(NULL));
			}
		}
	
	}
	imlib_context_set_image(_OsdImage);
	if (_Out) _Out->refresh();
	imlib_context_set_image(_OsdImage);
}

// --- cSoftOsdProvider -----------------------------------------------
cSoftOsdProvider::cSoftOsdProvider(FbRenderer *Out)
{
	_Out = Out;
}

cOsd * cSoftOsdProvider::CreateOsd(int Left, int Top)
{
	osd = new cSoftOsd(_Out, Left, Top);
	return osd;
}
