/*
** EPITECH PROJECT, 2018
** task01
** File description:
** I do task
*/
#include <stdlib.h>
#include "game/memory.h"
#include "game/core.h"

static void init_bullet(object_t *object, thrower_t *thrower)
{
	object->dx = (thrower->action == ID_THROWER_LEFT) ? BULLET_SPEED : 0;
	if (thrower->action == ID_THROWER_RIGHT)
		object->dx = -BULLET_SPEED;
	object->dy = (thrower->action == ID_THROWER_DOWN) ? BULLET_SPEED : 0;
	if (thrower->action == ID_THROWER_UP)
		object->dy = -BULLET_SPEED;
	object->x = thrower->x + 16;
	object->y = thrower->y + 16;
	object->sleep = 0;
}

object_t *init_object(thrower_t *thrower)
{
	object_t *object;

	object = (object_t*)malloc(sizeof(object_t));
	if (thrower->action == ID_THROWER_STONE){
		object->dx = (rand() % 9) - 4;
		object->dy = 0;
		object->x = thrower->x + 16;
		object->y = thrower->y + 16;
		object->sleep = 0;
		return (object);
	}
	init_bullet(object, thrower);
	return (object);
}

static thrower_t *setup_thrower(int i, int width, uint8_t action)
{
	thrower_t *thrower;
	int j;

	j = -1;
	thrower = (thrower_t*)malloc(sizeof(thrower_t));
	thrower->object = (object_t**)malloc(sizeof(object_t*) * NB_OBJECT);
	while (++j < NB_OBJECT)
		thrower->object[j] = NULL;
	thrower->x = (i - ((i / width) * width)) << 6;
	thrower->y = (i / width) << 6;
	thrower->action = action;
	return (thrower);
}

static thrower_t **get_thrower(uint8_t *map, int width,
int height, int thrower_counter)
{
	thrower_t **thrower;
	int counter;
	int i;

	i = -1;
	counter = 0;
	thrower = (thrower_t**)malloc(sizeof(thrower_t*) * thrower_counter);
	while (++i < width * height && counter < thrower_counter)
		if (map[i] >= ID_THROWER_STONE && map[i] <= ID_THROWER_RIGHT)
			thrower[counter++] = setup_thrower(i, width, map[i]);
	return (thrower);
}

thrower_t **init_thrower(level_t *level)
{
	int i;

	i = -1;
	level->thrower_counter = 0;
	while (++i < level->width * level->height)
		if (level->map[i] >= ID_THROWER_STONE
			&& level->map[i] <= ID_THROWER_RIGHT)
			level->thrower_counter++;
	if (!level->thrower_counter)
		return (NULL);
	level->timer_stone = 0;
	level->timer_bullet = 0;
	return (get_thrower(level->map, level->width,
	level->height, level->thrower_counter));
}
