#include "object.h"

#include <comdef.h>

#include "application_class.h"
#include "d_3d_class.h"

object::object(application_class& app) : m_Application(app)// initialize the reference here
{
	m_scaleMatrix = XMMatrixIdentity();
	m_rotateMatrix = XMMatrixIdentity();
	m_translateMatrix = XMMatrixIdentity();
	m_srMatrix = XMMatrixIdentity();
	m_worldMatrix = XMMatrixIdentity();
	m_previousPosition = XMVectorZero();
	m_velocity = XMVectorZero();
	m_acceleration = XMVectorZero();
	m_mass = NULL;
	m_isGrounded = false;
	m_id = NULL;
	m_boundingRadius = 1.0f;
}

object::object()
	: m_Application(*static_cast<application_class*>(nullptr)) // Remplacer suivant votre logique
{
	m_scaleMatrix = XMMatrixIdentity();
	m_rotateMatrix = XMMatrixIdentity();
	m_translateMatrix = XMMatrixIdentity();
	m_srMatrix = XMMatrixIdentity();
	m_worldMatrix = XMMatrixIdentity();
	m_previousPosition = XMVectorZero();
	m_velocity = XMVectorZero();
	m_acceleration = XMVectorZero();
	m_mass = NULL;
	m_isGrounded = false;
	m_id = NULL;
	m_boundingRadius = 1.0f;
}

object::~object()
{
}

bool object::Initialize(
	ID3D11Device* device,
	ID3D11DeviceContext* deviceContext,
	char* modelFilename,
	TextureContainer& texturesContainer
	)
{

	std::string filename(modelFilename);
	auto it = g_model_cache.find(filename);
	if (it != g_model_cache.end())
	{
		m_model_ = it->second;
	}
	else
	{
		auto new_model = std::make_shared<model_class>();
		if (!new_model->Initialize(device, deviceContext, modelFilename, texturesContainer))
		{
			return false;
		}
		g_model_cache[filename] = new_model;
		m_model_ = new_model;
	}

	return true;
}

void object::SetScaleMatrix(XMMATRIX scaleMatrix)
{
	m_scaleMatrix = scaleMatrix;
}

void object::SetRotateMatrix(XMMATRIX rotateMatrix)
{
	m_rotateMatrix = rotateMatrix;
}

void object::SetTranslateMatrix(XMMATRIX translateMatrix)
{
	m_translateMatrix = translateMatrix;
}

void object::SetSRMatrix(XMMATRIX srMatrix)
{
	m_srMatrix = srMatrix;
}

void object::SetWorldMatrix(XMMATRIX worldMatrix)
{
	m_worldMatrix = worldMatrix;
}

XMMATRIX object::GetScaleMatrix() const
{
	return m_scaleMatrix;
}

XMMATRIX object::GetRotateMatrix() const
{
	return m_rotateMatrix;
}

XMMATRIX object::GetTranslateMatrix() const
{
	return m_translateMatrix;
}

XMMATRIX object::GetSRMatrix() const
{
	return m_srMatrix;
}

XMMATRIX object::GetWorldMatrix() const
{
	return m_worldMatrix;
}

XMVECTOR object::GetPosition()
{
	XMFLOAT4X4 matrix;
	XMStoreFloat4x4(&matrix, m_translateMatrix);
	return XMVectorSet(matrix._41, matrix._42, matrix._43, 0.0f);
}

XMVECTOR object::GetRotation()
{
	XMFLOAT4X4 matrix;
	XMStoreFloat4x4(&matrix, m_rotateMatrix);
	float rotationX = atan2f(matrix._32, matrix._33);
	float rotationY = atan2f(-matrix._31, sqrtf(matrix._32 * matrix._32 + matrix._33 * matrix._33));
	float rotationZ = atan2f(matrix._21, matrix._11);
	return XMVectorSet(rotationX, rotationY, rotationZ, 0.0f);
}

XMVECTOR object::GetScale()
{
	XMFLOAT4X4 matrix;
	XMStoreFloat4x4(&matrix, m_scaleMatrix);

	// Utiliser des vecteurs pour les lignes de la matrice
	XMVECTOR row1 = XMLoadFloat3(reinterpret_cast<XMFLOAT3*>(&matrix._11));
	XMVECTOR row2 = XMLoadFloat3(reinterpret_cast<XMFLOAT3*>(&matrix._21));
	XMVECTOR row3 = XMLoadFloat3(reinterpret_cast<XMFLOAT3*>(&matrix._31));

	// Calculer les longueurs des vecteurs
	XMVECTOR scale = XMVectorSet(
		XMVectorGetX(XMVector3Length(row1)),
		XMVectorGetX(XMVector3Length(row2)),
		XMVectorGetX(XMVector3Length(row3)),
		0.0f
	);

	return scale;
}



void object::SetPosition(XMVECTOR position)
{
	XMFLOAT4X4 matrix;
	XMStoreFloat4x4(&matrix, m_translateMatrix);
	matrix._41 = XMVectorGetX(position);
	matrix._42 = XMVectorGetY(position);
	matrix._43 = XMVectorGetZ(position);
	m_translateMatrix = XMLoadFloat4x4(&matrix);
}

void object::SetRotation(XMVECTOR rotation)
{
	XMFLOAT4X4 matrix;
	XMStoreFloat4x4(&matrix, m_rotateMatrix);
	XMMATRIX rotationMatrix = XMMatrixRotationRollPitchYaw(XMVectorGetX(rotation), XMVectorGetY(rotation), XMVectorGetZ(rotation));
	m_rotateMatrix = rotationMatrix;
}

void object::SetScale(XMVECTOR scale)
{
	XMFLOAT4X4 matrix;
	XMStoreFloat4x4(&matrix, m_scaleMatrix);
	matrix._11 = XMVectorGetX(scale);
	matrix._22 = XMVectorGetY(scale);
	matrix._33 = XMVectorGetZ(scale);
	m_scaleMatrix = XMLoadFloat4x4(&matrix);
}

void object::UpdateWorldMatrix()
{
	m_worldMatrix = m_scaleMatrix * m_rotateMatrix * m_translateMatrix;
}

void object::UpdateSRMatrix()
{
	m_srMatrix = m_scaleMatrix * m_rotateMatrix;
}

void object::UpdateTranslateMatrix()
{
	m_translateMatrix = XMMatrixTranslationFromVector(GetPosition());
}

void object::UpdateRotateMatrix()
{
	m_rotateMatrix = XMMatrixRotationRollPitchYawFromVector(GetRotation());
}

void object::UpdateScaleMatrix()
{
	m_scaleMatrix = XMMatrixScalingFromVector(GetScale());
}

void object::Update()
{
	UpdateWorldMatrix();
	UpdateSRMatrix();
	UpdateTranslateMatrix();
	UpdateRotateMatrix();
	UpdateScaleMatrix();
}

std::string object::GetName()
{
	return m_name;
}

void object::SetName(std::string name)
{
	m_name = name;
}

void object::SetVelocity(XMVECTOR velocity)
{
	m_velocity = velocity;
}

void object::AddVelocity(float deltaTime)
{
	m_velocity += m_acceleration * deltaTime;
}

XMVECTOR object::GetVelocity() const
{
	return m_velocity;
}

void object::SetAcceleration(XMVECTOR acceleration)
{
	m_acceleration = acceleration;
}

XMVECTOR object::GetAcceleration() const
{
	return m_acceleration;
}

void object::SetMass(float mass)
{
	m_mass = mass;
}

float object::GetMass() const
{
	return m_mass;
}

void object::SetGrounded(bool isGrounded)
{
	m_isGrounded = isGrounded;
}

bool object::IsGrounded() const
{
	return m_isGrounded;
}

int object::SetId(int id)
{
	return m_id = id;
}

int object::GetId() const
{
	return m_id;
}

bool object::IsPhysicsEnabled() const
{
	return m_isPhysicsEnabled;
}

void object::SetPhysicsEnabled(bool state)
{
	m_isPhysicsEnabled = state;
}

float object::GetBoundingRadius() const
{
	return m_boundingRadius;
}

void object::UpdatePosition(float deltaTime)
{
	XMVECTOR position = GetPosition();
	position = position + GetVelocity() * deltaTime;
	SetPosition(position);
}

void object::SetType(ObjectType type)
{
	m_type = type;
}

std::string object::ObjectTypeToString(ObjectType type) {
	switch (type) {
		case ObjectType::Cube: return "Cube";
		case ObjectType::Sphere: return "Sphere";
		// Ajoutez d'autres cas si nécessaire
		default: return "Unknown";
	}
}

ObjectType object::StringToObjectType(const std::string& str) {
	if (str == "Cube") return ObjectType::Cube;
	if (str == "Sphere") return ObjectType::Sphere;
	// Add other cases as needed
	return ObjectType::Unknown;
}

std::string object::ShaderTypeToString(ShaderType type) {
	switch (type) {
		case ShaderType::ALPHA_MAPPING: return "ALPHA_MAPPING";
		case ShaderType::CEL_SHADING: return "CEL_SHADING";
		case ShaderType::NORMAL_MAPPING: return "NORMAL_MAPPING";
		case ShaderType::SPECULAR_MAPPING: return "SPECULAR_MAPPING";
		case ShaderType::TEXTURE: return "TEXTURE";
		case ShaderType::LIGHTING: return "LIGHTING";
		case ShaderType::SUNLIGHT: return "SUNLIGHT";
		// Ajoutez d'autres cas si nécessaire
		default: return "Unknown";
	}
}

ShaderType object::StringToShaderType(const std::string& str) {
	if (str == "ALPHA_MAPPING") return ShaderType::ALPHA_MAPPING;
	if (str == "CEL_SHADING") return ShaderType::CEL_SHADING;
	if (str == "NORMAL_MAPPING") return ShaderType::NORMAL_MAPPING;
	if (str == "SPECULAR_MAPPING") return ShaderType::SPECULAR_MAPPING;
	if (str == "TEXTURE") return ShaderType::TEXTURE;
	if (str == "LIGHTING") return ShaderType::LIGHTING;
	if (str == "SUNLIGHT") return ShaderType::SUNLIGHT;
	// Add other cases as needed
	return ShaderType::TEXTURE;
}

void object::LaunchObject()
{
	// Constants
	const float gravity = -9.81f;
    
	// Convert alpha from degrees to radians if needed
	float alphaRadians = m_alpha * (XM_PI / 180.0f);
    
	// Scale factors to make the physics simulation more visible
	float scaleFactor = 200.0f;  // Adjust this based on your world scale
    
	// Calculate initial velocity magnitude using the same formula as the Python code
	// v_eject = l1 * sqrt(k/m) * sqrt(1 - (m*g*sin(alpha)/(k*l1))^2)
	float velocityMagnitude = m_initialStretch * sqrtf(m_springConstant / m_mass) * 
							  sqrtf(1.0f - powf((m_mass * gravity * sinf(alphaRadians) / (m_springConstant * m_initialStretch)), 2.0f));
    
	// Apply scale factor
	velocityMagnitude *= scaleFactor;
    
	// Calculate velocity components
	XMVECTOR velocity = XMVectorSet(
		velocityMagnitude * cosf(alphaRadians),  // vx = v0 * cos(alpha)
		velocityMagnitude * sinf(alphaRadians),  // vy = v0 * sin(alpha)
		0.0f,                                   // z-component (0 for 2D trajectory)
		0.0f
	);
    
	// Apply velocity to object
	SetVelocity(velocity);
    
	// Enable physics for the object to handle the trajectory
	SetPhysicsEnabled(true);
    
	// Reset grounded state
	SetGrounded(false);
    
	// Debug output
	char buffer[256];
	sprintf_s(buffer, "Launch velocity: %f m/s at angle %f degrees", XMVectorGetX(XMVector3Length(velocity)), m_alpha);
	OutputDebugStringA(buffer);
}

bool object::LoadTexturesFromPath(std::vector<std::wstring>& texturePaths, TextureContainer& texturesContainer,
                                  d_3d_class* m_Direct3D)
{

	HRESULT result;
	
	int i = 0;
	TextureType type;
	for (const auto& texturePath : texturePaths)
	{
		ID3D11ShaderResourceView* texture = nullptr;
		result = DirectX::CreateWICTextureFromFile(m_Direct3D->get_device(), m_Direct3D->get_device_context(), texturePath.c_str(), nullptr, &texture);
		if (FAILED(result))
		{
			
			// Utiliser _com_error pour obtenir des informations détaillées sur l'erreur
			_com_error err(result);
			LPCTSTR errMsg = err.ErrorMessage();

			//convertie errMessage en std::wstring
			std::wstring ws(errMsg);
			std::string str(ws.begin(), ws.end());

			Logger::Get().Log("Failed to load texture: " + std::string(texturePath.begin(), texturePath.end()) +
				"\nError: " + std::to_string(result) +
				"\nDescription: " + str,
				__FILE__, __LINE__, Logger::LogLevel::Error);
			return false; // Assurez-vous de retourner false ou de gérer l'erreur de manière appropriée
		}
		texturesContainer.AssignTexture(texturesContainer, texture,texturePath , i);
		i++;
		
	}

	return true;
}