#include "GraphicNode.hpp"

//==============================================================================
// CONSTRUCTOR & DESTRUCTOR

/**
 * Constructor
 */
GraphicNode::GraphicNode(Agnode_t* np, double _resolution, QGraphicsItem * parent) :
    QGraphicsItem(parent),
    shapeBgColor(255, 255, 182, 255),
    shapePen(Qt::black),
    shapeBrush(shapeBgColor),
    rectItem(0),
    textItem(0),
    boundingBox(0, 0, 0, 0),
    RESOLUTION(_resolution)
{

  // Node center position (for shape and label)
  // Graphviz names changes in newer version: ND_coord_i (older versions) -> ND_coord (v2.26.3+)
  double centerX = ND_coord(np).x;
  double centerY = - ND_coord(np).y; // Invert Y axis

  //double centerX = 100;
  //double centerY = 100;

  //yMin = y < yMin ? y : yMin; // Keep track of Y to move whole graph at the end

  // Node shape size
  double width = RESOLUTION * ND_width(np);
  double height = RESOLUTION * ND_height(np);

  //@leonzo updates
  double topLeftX = centerX - width/2;
  double topLeftY = centerY - height/2;

  //maxHeight = height > maxHeight ? height : maxHeight; // Keep track of max shape height

  // Create rectangular item
  rectItem = new QGraphicsRectItem(QRectF(topLeftX, topLeftY, width, height), this);
  // TODO Use polygon instead of reactangle to create any shape

  // TODO use QTransform to scale object ?
  // QTransform transform;
  // transform.scale(RESOLUTION, RESOLUTION);
  // rectItem->setTransform(transform);

  // Node graphic attributes
  rectItem->setPen(shapePen);
  rectItem->setBrush(shapeBgColor);

  // Label content
  textlabel_t* label = ND_label(np);
  char* text = label->text;
  double fontSize = label->fontsize;
  char *fontName = label->fontname;
  //char* fontColor = label->fontcolor; // TODO

  // Create text item
  textItem = new QGraphicsSimpleTextItem(QString(text), this);
  textItem->setFont(QFont(QString(fontName), fontSize)); // XXX font size probme
  textItem->setPos(centerX - textItem->boundingRect().width()/2,
                   centerY - textItem->boundingRect().height()/2);

  // Init bounding box
  boundingBox.setRect( topLeftX,
                       topLeftY,
                       rectItem->boundingRect().width(),
                       rectItem->boundingRect().height());

}


/**
 * Destructor
 */
GraphicNode::~GraphicNode() {

  if (rectItem != 0)
    delete rectItem;

  if (textItem != 0)
    delete textItem;

}


//==============================================================================
// Methods

/**
 * @reimp
 */
QRectF GraphicNode::boundingRect() const {

  return boundingBox;

}

// TODO delete ?
/**
 * @reimp
 */
void GraphicNode::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget) {

  Q_UNUSED(painter);
  Q_UNUSED(option);
  Q_UNUSED(widget);

}

