#include "caporale.h"
#include "assets.h"
#include "game.h"
#include <raylib.h>
#include <raymath.h>

void initCaporale(Entity * entity, Game * game) {
	entity->model = &game->assets.models[CAPORATE_ASSET];
	entity->collisionModel = entityCreateCollisionModel(*entity->model);
	entity->transformedCollisionModel = entityCreateCollisionModel(*entity->model);
	setEntityRadius(entity);

	entity->health = 0.25;

	// Allocate data.
	entity->data = KF_MALLOC(sizeof(Caporale));

	if (entity->data == NULL) {
		ALLOCATION_ERROR;
		return;
	}

	Caporale * data = (Caporale*)entity->data;

	data->flyToPlayer = (EntityFlyToPointInfo){
		.controller.bangbang.speed = 80,
		.controller.bangbang.stopAt = 0.0,
		.controlType = ENTITY_FLY_TO_POINT_BANG_BANG,
		.rotationSpeed = 0.5,
		.applyRotation = true
	};

	data->timeSinceLastShot = 0.0;
	data->gunTarget = Vector3One();
}

void closeCaporale(Entity * entity) {
	if (entity->data != NULL)
		KF_FREE(entity->data);

	entityFreeCollisionModel(entity->collisionModel);
	entityFreeCollisionModel(entity->transformedCollisionModel);
}

void updateGunsCaporale(Game * game, Entity * entity) {
	double t = GetTime();
	Caporale * data = (Caporale*)entity->data;
	Entity * player = getEntityFromWorld(game->world, 0);

	// Update gun target.
	Vector3 target = Vector3Normalize(Vector3Subtract(player->position, entity->position));
	data->gunTarget = Vector3Lerp(data->gunTarget, target, GetFrameTime() * CAPORALE_GUN_TARGETING_SPEED);

	// Cool down.
	if (t - data->timeSinceLastShot < CAPORALE_COOLDOWN)
		return;

	data->timeSinceLastShot = t;

	float damage = CAPORALE_BULLET_DAMAGE;

	if (entity->health <= CAPORALE_LOW_HEALTH_THRESHOLD)
		damage = CAPORALE_LOW_HEALTH_BULLET_DAMAGE;

	// Create bullet and shoot.
	Bullet bullet = createBulletFromDirection(*entity, data->gunTarget, damage);
	shootBulletAtEntity(player, bullet);
}

void updateCaporale(Game * game, Entity * entity) {
	entityUpdateLastValues(entity);

	Caporale * data = (Caporale*)entity->data;
	Entity * player = getEntityFromWorld(game->world, 0);

	entityFlyToPoint(entity, player->position, &data->flyToPlayer);
	updateGunsCaporale(game, entity);

	entityCheckTransformedCollisionModel(entity);
}

void drawCaporale(Game * game, Entity * entity) {
	entityDraw(entity);
}