/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   screen.c                                           :+:    :+:            */
/*                                                     +:+                    */
/*   By: qmennen <qmennen@student.codam.nl>           +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/04/15 15:30:27 by qmennen       #+#    #+#                 */
/*   Updated: 2025/05/23 15:17:59 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "screen.h"

int	screen_create(t_game **game)
{
	t_screen	*screen;
	mlx_t		*mlx;

	screen = malloc(sizeof(t_screen));
	if (!screen)
		return (FAILURE);
	screen->width = WIDTH;
	screen->height = HEIGHT;
	mlx_set_setting(MLX_FULLSCREEN, 0);
	mlx = mlx_init(WIDTH, HEIGHT, TITLE, true);
	if (!mlx)
		return (FAILURE);
	screen->mlx = mlx;
	screen->img = mlx_new_image(screen->mlx, WIDTH + 50, HEIGHT + 50);
	if (!screen->img)
		return (FAILURE);
	screen->minimap = mlx_new_image(screen->mlx, WIDTH, HEIGHT);
	if (!screen->minimap)
		return (FAILURE);
	screen->background = mlx_new_image(screen->mlx, WIDTH, HEIGHT);
	if (!screen->background)
		return (FAILURE);
	(*game)->screen = screen;
	return (SUCCESS);
}

void	fill_background(t_screen *screen, int color)
{
	int	i;
	int	j;

	i = 0;
	while (i < screen->width)
	{
		j = 0;
		while (j < screen->height)
		{
			mlx_put_pixel(screen->background, i, j, color);
			j++;
		}
		i++;
	}
}

int	center_window(t_screen *screen)
{
	int	m_width;
	int	m_height;

	m_width = 0;
	m_height = 0;
	mlx_get_monitor_size(0, &m_width, &m_height);
	if (m_width == 0 || m_height == 0)
	{
		printf(RED"Failed to retrieve monitor size to center window\n"RESET);
		return (FAILURE);
	}
	mlx_set_window_pos(screen->mlx, (m_width - screen->width) / 2,
		(m_height - screen->height) / 2);
	return (SUCCESS);
}

int	screen_display(t_screen *screen)
{
	fill_background(screen, 0x000000FF);
	if (mlx_image_to_window(screen->mlx, screen->background, 0, 0) < 0)
	{
		printf(RED"Failed to display buffer image\n"RESET);
		return (FAILURE);
	}
	if (mlx_image_to_window(screen->mlx, screen->img, 0, 0) < 0)
	{
		printf(RED"Failed to display buffer image\n"RESET);
		return (FAILURE);
	}
	if (mlx_image_to_window(screen->mlx, screen->minimap, 175, 575) < 0)
	{
		printf(RED"Failed to display buffer image\n"RESET);
		return (FAILURE);
	}
	if (mlx_image_to_window(screen->mlx, screen->hud, 0, 0) < 0)
	{
		printf(RED"Failed to display buffer image\n"RESET);
		return (FAILURE);
	}
	if (!center_window(screen))
		return (FAILURE);
	return (SUCCESS);
}
