/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   screen.c                                           :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: qmennen <qmennen@student.codam.nl>         +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2025/04/15 15:30:27 by qmennen           #+#    #+#             */
/*   Updated: 2025/06/03 20:20:36 by qmennen          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "screen.h"

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

	screen = malloc(sizeof(t_screen));
	if (!screen)
		return (FAILURE);
	ft_memset(screen, 0, sizeof(t_screen));
	screen->width = WIDTH;
	screen->height = HEIGHT;
	mlx_set_setting(MLX_FULLSCREEN, FULLSCREEN);
	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(mlx_image_t *image, int color)
{
	int	i;
	int	j;

	i = 0;
	while (i < image->width)
	{
		j = 0;
		while (j < image->height)
		{
			mlx_put_pixel(image, 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)
		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)
{
	int	display_error;
	fill_background(screen->background, 0x000000FF);

	display_error = 0;
	display_error |= mlx_image_to_window(screen->mlx, screen->background, 0, 0) < 0;
	display_error |= mlx_image_to_window(screen->mlx, screen->img, 0, 0) < 0;
	display_error |= mlx_image_to_window(screen->mlx, screen->minimap, 175, 575) < 0;
	display_error |= mlx_image_to_window(screen->mlx, screen->hud, 0, 0) < 0;

	if (display_error || !center_window(screen))
	{
		printf(RED "Display failed to initialize\n" RESET);
		return (FAILURE);
	}
	screen->hud->instances[0].enabled = false;
	screen->minimap->instances[0].enabled = false;
	return (SUCCESS);
}
