#include "gameplay/entity.h"
#include "gameplay/camera.h"
#include "gameplay/physics.h"

void Entity::setPosition(const glm::vec3& position)
{
	this->position = position;
	updateModelMatrix();
}
void Entity::setScale(const glm::vec3& scale)
{
	this->scale = scale;
	updateModelMatrix();
}
void Entity::setRotation(const float& rotation)
{
	this->rotation = rotation;
	updateModelMatrix();
}

void Entity::setLocalPosition(const glm::vec3& localPosition)
{
	this->localPosition = localPosition;
}

void Entity::setRotatable(bool rotatable)
{
	this->isRotatable = rotatable;
}

void Entity::flip()
{
	flipped = !flipped;
}

void Entity::addPhysicsComponent(const std::shared_ptr<PhysicsComponent>& physics)
{
	this->physics = physics;
}

void Entity::update(double deltaTime)
{
	if (physics && physics->rigidBody.velocity != glm::vec3(0.0f))
	{
		position = physics->rigidBody.position;
		updateModelMatrix();
		deltaPosition = glm::vec3(0.0f);
	}
	else if (!physics)
	{
		position += deltaPosition * 1.f;
		updateModelMatrix();
		deltaPosition = glm::vec3(0.f);
	}
}

void Entity::draw()
{
	//glm::mat4 mvp = camera->getProjectionMatrix() * camera->getViewMatrix() * modelMatrix;
	editUniform("model", modelMatrix);
	editUniform("flip", flipped);
}

void Entity::updateModelMatrix()
{
	glm::mat4 rotationMat = (isRotatable) ? glm::rotate(glm::mat4(1.f), glm::radians(rotation), glm::vec3(0.0f, 0.0f, 1.0f)) : glm::mat4(1.0f);
	glm::mat4 translation = glm::translate(glm::mat4(1.f), position);
	modelMatrix =
		translation *
		rotationMat *
		glm::scale(glm::mat4(1.0f), scale);
}
