#include "picmapmac.h"
#include <UDebugging.h>

static int NTotAllocCol;


PIColorMapMac::PIColorMapMac()
: PIColorMapGen(), mPalette(NULL), mCTab(NULL)
{
}

PIColorMapMac::PIColorMapMac(int id, int nc, string const& nom) 
: PIColorMapGen(id, nc, nom)
{
    int n = nc+2;
	mCTab = (CTabHandle) ::NewHandle(sizeof(long) + 
				sizeof(short) + sizeof(short) + 
				n*sizeof(ColorSpec));
	(**mCTab).ctFlags = 0;
	(**mCTab).ctSeed = GetCTSeed();
	(**mCTab).ctSize = n;
    ColorSpec* sp = (**mCTab).ctTable;
    sp[0].rgb.red   = 0;
    sp[0].rgb.green = 0;
    sp[0].rgb.blue  = 0;
    sp[0].value     = 0;
    sp[1].rgb.red   = 65535;
    sp[1].rgb.green = 65535;
    sp[1].rgb.blue  = 65535;
    sp[1].value     = 1;
    for (int i=2; i<n; i++) {
      sp[i].rgb.red   = 0;
      sp[i].rgb.green = 0;
      sp[i].rgb.blue  = 0;
      sp[i].value     = i;
    }
  mPalette = NewPalette(mNCol,mCTab,pmTolerant,0);
}

PIColorMapMac::~PIColorMapMac()
{
  DisposePalette(mPalette);
  DisposeHandle((Handle)mCTab);
}

/* --Methode-- */
PIColor PIColorMapMac::GetColor(int n)
{
PIColor picr;
picr.red = picr.green = picr.blue = 0;

if ((n<0) || (n >= NCol()))   
  return(picr);

RGBColor qdCol;
GetEntryColor(mPalette,n+2,&qdCol);

picr.red   = qdCol.red;
picr.green = qdCol.green;
picr.blue  = qdCol.blue;

return(picr);
}


bool PIColorMapMac::AllocColor(PIColor const& col, int index)
{
  if (!mPalette) return false;
  if ((index < 0) || (index > mNCol))  return(false);
  
  RGBColor srcRGB;
  srcRGB.red   = col.red;
  srcRGB.green = col.green;
  srcRGB.blue  = col.blue;
  
  SetEntryColor(mPalette,index+2,&srcRGB);
  ((**mCTab).ctTable)[index+2].rgb = srcRGB;
  NTotAllocCol++;
  return true;    //  $CHECK$  retourne true si OK - Reza 01/12/97
}

long PIColorMapMac::TotNbColors()
{
   PixMapHandle pmh = ((CGrafPort*)qd.thePort)->portPixMap;
   int depth = (**pmh).cmpSize * (**pmh).cmpCount;
   long nbcol = 1;
   for (int i=0; i<depth; i++)
     nbcol *= 2;
   return nbcol;
}

void PIColorMapMac::FreeColors()
{
  Assert_(mPalette);
  DisposePalette(mPalette);
  DisposeCTable(mCTab);
}

int PIColorMapMac::NbAllocColors()
{
return(NTotAllocCol);
}


void PIColorMapMac::CopyFrom(PIColorMapGen* x)
{
  CopyFromGen(x);
  PIColorMapMac* y = (PIColorMapMac*) x;
  mPalette = y->mPalette;
  mCTab = y->mCTab;
  HandToHand(&(Handle)mCTab);
  HandToHand(&(Handle)mPalette);
  Assert_(mPalette);
}
