#include "region.h"
#include <vdr/osd.h>
#include <vdr/tools.h>
#include "configuration.h"
#include "clut.h"

Region::Region( int aId )
    :iId(aId),iCanvas(0),bpp(2),loc(2)
{
  Reset();
}

Region::~Region()
{
  if ( iCanvas )
    delete iCanvas;
  Reset();
}

void Region::SetClut( Clut* aClut )
{

  iClut = aClut;

}

void Region::Draw( int aX, int aY, int aPixelCode, int rl)
{

    
    if ( iCanvas == NULL )
    {
	return;
    }

    // quantize to required  2bpp
    if (gSubtitlesConfiguration.dxr3comp)
    {
	int pixelCode = 0;
	if (aPixelCode & 0x8)
	    pixelCode |= 0x2;
	if (aPixelCode & 0x7)
	    pixelCode |= 0x1;
	aPixelCode = pixelCode;
    }

    const cSubtitlesPalette* palette  = iClut->GetPalette(4);

    if (palette == NULL)
    {
	return;
    }


    int numColors;
    const uint32_t* colors;
    if (gSubtitlesConfiguration.dxr3comp)
    {
	numColors = 4;
	static uint32_t __colors[] = {clrTransparent, clrBlack, clrWhite, clrWhite};
	colors = __colors;
    }
    else
    {
	numColors= palette->GetNumColors();
	colors = palette->GetColors();
    }

    if (aPixelCode >= 0  && aPixelCode < numColors)
    {
      if (rl == 1)
	iCanvas->DrawPixel (aX, aY, colors[aPixelCode]);
      else
	iCanvas->DrawRectangle (aX, aY, aX + rl - 1, aY, colors[aPixelCode]);
    }
}


void Region::Reset()
{

  iClut = 0;
  iWidth = 0;
  iHeight = 0;
  iX = 0;
  iY = 0;

}

void Region::SetSize( int aWidth, int aHeight ) 
{

  iWidth = aWidth;
  iHeight = aHeight;
  Create();

}

void Region::SetPosition( int aX, int aY )
{

  iX = aX;
  iY = aY;
}

void Region::Create( void )
{
    if (iCanvas)
	delete iCanvas;
    iCanvas = new cBitmap( iWidth, iHeight, gSubtitlesConfiguration.dxr3comp?2:4 );
    iCanvas->Reset();
}

int Region::X()
{
  return iX;
}

int Region::Y()
{
  return iY;
}


int Region::Width()
{
  return iWidth;
}

int Region::Height()
{
  return iHeight;
}


void Region::SetBpp(int Bpp, int Loc)
{

    bpp = Bpp;
    loc = Loc;
}

int Region::Id()
{

  return iId;

}

cBitmap* Region::Canvas( void )
{
  return iCanvas;

}
