#include "Projectile.h"

namespace ZL {

	Projectile::Projectile()
		: pos({ 0,0,0 })
		, vel({ 0,0,0 })
		, life(0.0f)
		, maxLife(0.0f)
		, active(false)
		, size(0.5f)
		, texture(nullptr)
	{
	}

	void Projectile::init(const Vector3f& startPos, const Vector3f& startVel, float lifeMs, float s, std::shared_ptr<Texture> tex, Renderer& renderer) {
		pos = startPos;
		vel = startVel;
		life = 0.0f;
		maxLife = lifeMs;
		size = s;
		texture = tex;
		active = true;

		rebuildMesh(renderer);
		mesh.RefreshVBO();
	}

	void Projectile::update(float deltaMs, Renderer& renderer) {
		if (!active) return;

		pos = pos + vel * (deltaMs / 1000.0f);
		life += deltaMs;
		if (life >= maxLife) {
			active = false;
			return;
		}

		rebuildMesh(renderer);
		mesh.RefreshVBO();
	}

	void Projectile::rebuildMesh(Renderer&) {
		float half = 10 * size * 0.5f;

		mesh.data.PositionData.clear();
		mesh.data.TexCoordData.clear();

		mesh.data.PositionData.push_back({ pos(0) - half, pos(1) - half, pos(2) });
		mesh.data.PositionData.push_back({ pos(0) - half, pos(1) + half, pos(2) });
		mesh.data.PositionData.push_back({ pos(0) + half, pos(1) + half, pos(2) });

		mesh.data.PositionData.push_back({ pos(0) - half, pos(1) - half, pos(2) });
		mesh.data.PositionData.push_back({ pos(0) + half, pos(1) + half, pos(2) });
		mesh.data.PositionData.push_back({ pos(0) + half, pos(1) - half, pos(2) });

		mesh.data.TexCoordData.push_back({ 0.0f, 0.0f });
		mesh.data.TexCoordData.push_back({ 0.0f, 1.0f });
		mesh.data.TexCoordData.push_back({ 1.0f, 1.0f });
		mesh.data.TexCoordData.push_back({ 0.0f, 0.0f });
		mesh.data.TexCoordData.push_back({ 1.0f, 1.0f });
		mesh.data.TexCoordData.push_back({ 1.0f, 0.0f });
	}

	void Projectile::draw(Renderer& renderer) const {
		if (!active || !texture) return;
		glBindTexture(GL_TEXTURE_2D, texture->getTexID());
		renderer.DrawVertexRenderStruct(mesh);
	}

} // namespace ZL