/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   keyhook.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: pblagoje <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/05/04 13:45:52 by pblagoje          #+#    #+#             */
/*   Updated: 2022/05/04 17:23:50 by hulamy           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "cube3d.h"

static int	print_keycode(int keycode, t_plr *plr)
{
	ft_putnbr_fd(keycode, 1);
	ft_putchar_fd(' ', 1);
	ft_putnbr_fd(plr->rot, 1);
	ft_putchar_fd('\n', 1);
	return (0);
}


int should_ignore_keypress(const struct timeval *current_time, t_game *game)
{ 
	int is_less;  
	unsigned long current_milliseconds;
	unsigned long last_milliseconds;

	current_milliseconds = (current_time->tv_sec % 1000) * 1000 + current_time->tv_usec / 1000;
	last_milliseconds = (game->last_keypress_time.tv_sec % 1000) * 1000 + game->last_keypress_time.tv_usec / 1000;
	is_less = (current_milliseconds - last_milliseconds) < DEBOUNCE_TIME;

	if (!is_less)
		game->last_keypress_time = *current_time;
	return is_less;
}


int	hook_action(t_game *game)
{
	int	is_action;
	struct timeval current_time;

	gettimeofday(&current_time, NULL);
	if (should_ignore_keypress(&current_time, game))
		return (0);

	is_action = 0;
	if (is_esc(game->k_hook, &is_action))
		shut_down();
	if (is_go_left(game->k_hook, &is_action))
		plr_posx_decrement(game, &(game->plr));
	if (is_go_right(game->k_hook, &is_action))
		plr_posx_increment(game, &(game->plr));
	if (is_go_forward(game->k_hook, &is_action))
		plr_posy_decrement(game, &(game->plr));
	if (is_go_backward(game->k_hook, &is_action))
		plr_posy_increment(game, &(game->plr));
	if (is_turn_left(game->k_hook, &is_action))
		plr_turn_left(&(game->plr));
	if (is_turn_right(game->k_hook, &is_action))
		plr_turn_right(&(game->plr));
	if (is_action)
		draw(game);
	return (0);
}

int	keypress(int keycode, t_game *game)
{
	unsigned int	i;

	print_keycode(keycode, &game->plr);
	i = 0;
	while (i < MAX_NB_KEY && game->k_hook[i] != 0 && game->k_hook[i] != keycode)
		i++;
	if (game->k_hook[i] == keycode && i < MAX_NB_KEY)
		game->k_hook[i] = 0;
	else if (i < MAX_NB_KEY)
		game->k_hook[i] = keycode;
	return (0);
}

int	keyrelease(int keycode, t_game *game)
{
	unsigned int	i;

	i = 0;
	while (i < MAX_NB_KEY && game->k_hook[i] != keycode)
		i++;
	if (i < MAX_NB_KEY)
		game->k_hook[i] = 0;
	return (0);
}
