#include "GraphicFrame.h"

#include <vector>
#include <string>
using namespace std;

GraphicFrame::GraphicFrame ()
{
  refCount = 0;
  primList.clear();
  bitmapList.clear();
  nextObjectToDraw.clear();
  atms.clear();
}

GraphicFrame::~GraphicFrame ()
{
}
  
void GraphicFrame::incRefCount ()
{
  if (refCount < 2 ^ 32)
    refCount ++;
}

void GraphicFrame::decRefCount ()
{
  if (refCount > 0)
    refCount --;
}

uint32_t GraphicFrame::getRefCount ()
{
  return refCount;
}

vector<string> & GraphicFrame::getGraphicPrimitiveList ()
{
  return primList;
}

vector<string> & GraphicFrame::getGraphicBitmapList ()
{
  return bitmapList;
}

int GraphicFrame::getNumberOfElements ()
{
  return nextObjectToDraw.size();
}

bool GraphicFrame::addReference (const string & type, const string & name, const AffineTransformationMatrix & atm)
{
  //adds a reference. Returns true if it understands the type of reference and name is not "NULL_INDEX"
  string nam = name;

  if (name.empty() || name=="NULL_INDEX")
    return false;

  if (type=="Primitive")
    {
      nextObjectToDraw.push_back(GRAPHIC_PRIMITIVE);
      primList.push_back(nam);
    }
  else if (type=="Bitmap")
    {
      nextObjectToDraw.push_back(GRAPHIC_BITMAP);
      bitmapList.push_back(nam);
    }
  else
    return false;

  atms.push_back(atm);
  return true;
}

bool GraphicFrame::getReference(uint8_t index, string & type, string & name, AffineTransformationMatrix & atm)
{
  //given the index, this will return the indexth object in the graphic frame.
  //This sets type to the type of object (matching addReference,) the name of the object and its relative coordinates. Returns true.
  //If index is out of bounds, type is set to "out of bounds" and name is set to "NULL_INDEX" and returns false
  if (index >= nextObjectToDraw.size())
    {
      type = "out of bounds";
      name = "NULL_INDEX";
      return false;
    }

  //We're going to run through nextObjectToDraw to figure out which object we should retrieve.
  uint8_t typeToDraw=255;
  uint8_t i=0;
  int16_t primitiveIndex=-1, bitmapIndex=-1;

  for (i=0; i<=index && i<nextObjectToDraw.size(); i++)
    {
      typeToDraw=nextObjectToDraw[i];
      if (typeToDraw == GRAPHIC_PRIMITIVE)
	primitiveIndex++;
      else if(typeToDraw == GRAPHIC_BITMAP)
	bitmapIndex++;
    }

  if (typeToDraw==GRAPHIC_PRIMITIVE)
    {
      type="Primitive";
      name=primList[primitiveIndex];
    }
  else if (typeToDraw==GRAPHIC_BITMAP)
    {
      type="Bitmap";
      name=bitmapList[bitmapIndex];
    }
  else
    {
      type="out of bounds";
      name="NULL_INDEX";
      return false;
    }
  
  atm=atms[index];
  return true;
}
