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

static void update_camera_dead(scene_t *scene)
{
	scene->camera->x += rand() % CAMERA_SHAKY;
	scene->camera->y += rand() % CAMERA_SHAKY;
	scene->player->dead_counter++;
	if (scene->player->dead_counter >= PLAYER_DEAD_TIME * 3){
		scene->player->x = scene->player->start_x;
		scene->player->y = scene->player->start_y;
		if (scene->wall != NULL)
			scene->wall->x = scene->player->x - (WALL_SIZE << 2);
		scene->player->action = PLAYER_IDLE | PLAYER_LEFT;
		scene->player->dead_counter = 0;
		scene->player->frame_counter = 0;
		scene->player->dx = 0;
		scene->player->dy = 0;
		scene->player->nb_dead++;
	}
}

static void fix_camera(scene_t *scene, int width, int height)
{
	if (scene->camera->x < 0)
		scene->camera->x = 0;
	if (scene->camera->y < 0)
		scene->camera->y = 0;
	if (scene->camera->x + width > scene->level->width << 6)
		scene->camera->x = (scene->level->width << 6) - width;
	if (scene->camera->y + height > scene->level->height << 6)
		scene->camera->y = (scene->level->height << 6) - height;
}

void game_camera_update(scene_t *scene, int width, int height)
{
	int dx;
	int dy;

	dx = scene->player->x - (width >> 1) - scene->camera->x;
	dy = scene->player->y - (height >> 1) - scene->camera->y;
	scene->camera->x = (my_abs(dx) > CAMERA_SPEED)
	? scene->camera->x + CAMERA_SPEED * ((dx < 0) ? -1 : 1)
: scene->player->x - (width >> 1);
	scene->camera->y = (my_abs(dy) > CAMERA_SPEED)
	? scene->camera->y + CAMERA_SPEED * ((dy < 0) ? -1 : 1)
: scene->player->y - (height >> 1);
	fix_camera(scene, width, height);
	if (scene->player->action & PLAYER_DEAD)
		update_camera_dead(scene);
}
