#include "gameobject.h"

#include <GL/glew.h>
#include <glm/gtc/type_ptr.hpp>

#include "internal.h"
#include "internal/physics.h"

namespace kek {

GameObject::GameObject() {
	this->physics = nullptr;
}

GameObject::~GameObject() {
	for(Mesh *mesh : meshes) {
		delete mesh;
	}
}

void GameObject::addMesh(Mesh *mesh) {
	meshes.push_back(mesh);
}

void GameObject::draw(Shader *shader) {
	glm::mat4 model = glm::mat4(1.0f);
	model = glm::translate(model, getPosition()) * glm::mat4_cast(getRotation());
	glUniformMatrix4fv(glGetUniformLocation(kekData.shader->id, "model"), 1, GL_FALSE, glm::value_ptr(model));

	for(Mesh *mesh : meshes) {
		mesh->draw(shader);
	}
}

void GameObject::addPhysics(btCollisionShape *shape, float mass, int collisionFlags) {
	this->physics = new PhysicsObjectData();
	btVector3 inertia = btVector3(0,0,0);
	shape->calculateLocalInertia(mass, inertia);
	btRigidBody *body = new btRigidBody(mass, new btDefaultMotionState(), shape, inertia);
	body->setFriction(1);
	kekData.physics->world->addRigidBody(body);
	body->setCollisionFlags(body->getCollisionFlags() | collisionFlags);
	this->physics->body = body;
}

void GameObject::rotateTo(glm::quat rotation) {
	this->physics->body->getWorldTransform().setRotation(Physics::fromGLM(rotation));
}

glm::quat GameObject::getRotation() {
	return Physics::toGLM(this->physics->body->getWorldTransform().getRotation());
}

void GameObject::moveTo(glm::vec3 position) {
	this->physics->body->getWorldTransform().setOrigin(Physics::fromGLM(position));
}

glm::vec3 GameObject::getPosition() {
	return Physics::toGLM(this->physics->body->getWorldTransform().getOrigin());
}

}
