//#include <graphite.h>
#include <stdlib.h>
#include <iostream>
// must be before graphite files to avoid name conflict over Font
#include <X11/Xft/Xft.h> 

#include "sila.h"
#include "DrawGraphiteString.h"

#define OutputDebugStringA(x) std::cout << x

#include "prtypes.h"

#include "GrUtfTextSrc.h"
#include <graphite/SegmentPainter.h>
#include <graphite/XftGrFont.h>
#include "nsXftPainterFactory.h"
#include "nsAutoDrawSpecBuffer.h"

using namespace gr;

int DrawGraphiteString(Display * display, XftDraw *xftDraw, XftFont *xftFont, int x, int y, utf16 * grstring, int size)
{
  GrUtfTextSrc textSrc;
  textSrc.setText(grstring, size);
  //textSrc.setColors(0x00, kclrTransparent);
  textSrc.setColors(0x00, 0x00ffff);
  // create segment
  LayoutEnvironment layout;
  layout.setEndOfLine(false);
  layout.setStartOfLine(false);
  layout.setDumbFallback(true);
  layout.setJustifier(NULL);
  try 
  {
    XftGrFont grFont(xftFont); 
    RangeSegment seg(&grFont, &textSrc, &layout, 0, size); 
    // paint
    nsXftPainterFactory painterFactory;
    nsAutoDrawSpecBuffer adsBuffer(xftDraw, NULL, display);
    painterFactory.setDraw(xftFont, xftDraw, &adsBuffer);
    SegmentPainter * pPainter = painterFactory.getPainter(&seg);
    printf("position %d %d\n", x, y);
    //pPainter->setScalingFactors(72,72);
    //pPainter->setOrigin(0,0);
    // centre the text on the x position
    float xOffset = 0.5 * seg.advanceWidth();
    pPainter->setOrigin(static_cast<float>(x) - xOffset, static_cast<float>(y));
    pPainter->paint();
    delete pPainter;
  }
  catch (...)
  {
    printf("Error in rendering");
  }
  return kresOk;
}

bool IsGraphiteFont(XftFont * xftFont)
{
  return XftGrFont::FontHasGraphiteTables(xftFont);
}
