/*
 * Copyright (C) 2003-2004, 2012 Clemens Fuchslocher
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 */

#include <GL/gl.h>
#include <GL/glu.h>

#include <cstdlib>
#include <typeinfo>

#include "SceneGraphVisitor.h"
#include "GlActionVisitor.h"
#include "Transform.h"


namespace nsSceneGraph {

Transform::Transform(void) : GraphNode(TRANSFORM, "TRANSFORM")
{
	DEBUG_MESSAGE("Transform::Transform()")

	this->center[0] = this->center[1] = this->center[2] = 0.0;
	this->rotation[0] = this->rotation[1] = this->rotation[2]  = this->rotation[3] = 0.0;
	this->translation[0] = this->translation[1] = this->translation[2] = 0.0;
}


Transform::~Transform(void)
{
	DEBUG_MESSAGE("Transform::~Transform")

	if (this->isNodeCompiled())
	{
		glDeleteLists(this->getCompiledDisplayList(), 1);
	}
}


int Transform::action(SceneGraphVisitor *visitor)
{
	DEBUG_MESSAGE("Transform::accept()")

	/*
	 * Using RTTI this way is ugly like hell. But I can't
	 * find another way, which won't break the simplicity
	 * of the visitor pattern. :-/
	 */
	bool glActionVisitor = (typeid(*visitor) == typeid(GlActionVisitor));
	if (glActionVisitor)
	{
		glPushMatrix();
	}

	visitor->visit(this);

	GraphNode::action(visitor);

	if (glActionVisitor)
	{
		glPopMatrix();
	}

	return SG_OK;
}

void Transform::setCenter(double x, double y, double z)
{
	this->setCompiledStatus(false);

	this->center[0] = x;
	this->center[1] = y;
	this->center[2] = z;
}


void Transform::setRotation(double angle, double rx, double ry, double rz)
{
	this->setCompiledStatus(false);

	this->rotation[0] = rx;
	this->rotation[1] = ry;
	this->rotation[2] = rz;
	this->rotation[3] = angle;
}


void Transform::setTranslation(double x, double y, double z)
{
	this->setCompiledStatus(false);

	this->translation[0] = x;
	this->translation[1] = y;
	this->translation[2] = z;
}


GraphNode *Transform::duplicate(void)
{
	std::cerr << __FILE__ << '[' << __LINE__ << "]: Transform::duplicate() isn't implemented yet." << std::endl;
	std::exit(SG_KO);

	return NULL;
}


}

