#include <QtGui>
#include <math.h>

#include "ScienceNode.h"
#include "ScienceTree.h"
#include "NodeWidget.h"

ScienceNode * NodeWidget::getLogicalNode()
{
	return logicalNode_;
}

void NodeWidget::setupRestSize()
{
	restWidth_ = width() - 2 - tokensWidth_ - pointsWidth_;
}

void NodeWidget::setupPointsSize()
{
	if (logicalNode_)
	{
		pointsWidth_ = nodeWidthRatio_ * (logicalNode_->getAssignedPoints() - logicalNode_->getAssignedTokens());		
		pointsHeight_ = height();

		setupRestSize();		
	}
}

void NodeWidget::setupNodeWidthRatio()
{
	unsigned long maximumTokens = logicalNode_->getMaximumTokens();

	if (maximumTokens > 0) {
		nodeWidthRatio_ = (width() - 4) / (double)maximumTokens;
	}
	else {
		nodeWidthRatio_ = 1;
	}
}

void NodeWidget::setupTokensSize()
{
	if (logicalNode_)
	{
		tokensWidth_ = nodeWidthRatio_ * (logicalNode_->getAssignedTokens());
		tokensHeight_ = height();

		setupRestSize();
	}
}

void NodeWidget::resizeEvent(QResizeEvent *)
{
	setupNodeWidthRatio();
	setupTokensSize();
	setupPointsSize();		 
}

void NodeWidget::paintEvent(QPaintEvent *)
{
	QPainter painter(this);

	painter.setRenderHint(QPainter::Antialiasing, true);
	painter.setPen(QPen(Qt::black, 12, Qt::DashDotLine, Qt::RoundCap));
	painter.setBrush(QBrush(Qt::green, Qt::SolidPattern));

	painter.fillRect(2, 2, tokensWidth_, tokensHeight_, Qt::yellow);
	painter.fillRect(tokensWidth_, 2, pointsWidth_, pointsHeight_, Qt::green);	

	painter.fillRect(tokensWidth_ + pointsWidth_, 2, restWidth_, pointsHeight_, QColor::fromRgb(141, 141, 141));
}

void NodeWidget::mousePressEvent(QMouseEvent *)
{
	emit mousePressSignal(this);
}

void NodeWidget::leaveEvent(QEvent *)
{
	
}

void NodeWidget::enterEvent(QEvent *)
{
	
}

NodeWidget::NodeWidget(QWidget * parent) : QFrame(parent)
{	
	logicalNode_ = NULL;
}

void NodeWidget::setLogicalNode(ScienceNode * logicalNode)
{
	logicalNode_ = logicalNode;

	setupNodeWidthRatio();

	setupTokensSize();
	setupPointsSize();	
}


void NodeWidget::setLabel(QLabel * label)
{
	label_ = label;
}