/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   xpm.c                                              :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cchauvet <cchauvet@student.42angouleme.fr  +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2023/01/04 13:53:03 by cchauvet          #+#    #+#             */
/*   Updated: 2023/01/16 18:14:56 by cchauvet         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "solong.h"

static char	*ft_square(size_t size)
{
	char	*map;
	size_t	x;
	size_t	y;

	map = malloc(((size + 4) * size) * sizeof(char));
	if (map == NULL)
		return (map);
	y = 0;
	while (y < size)
	{
		map[(size + 4) * y] = '"';
		x = 0;
		while (x < size)
		{
			map[y * (size + 4) + x + 1] = 'a';
			x++;
		}
		map[(size + 4) * y + size + 1] = '"';
		map[(size + 4) * y + size + 2] = ',';
		map[(size + 4) * y + size + 3] = '\n';
		y++;
	}
	map[(size + 4) * size - 2] = '\0';
	return (map);
}

char	*name_generator(t_square square)
{
	char	*out;
	char	*size;
	char	*temp;

	size = ft_itoa(square.size);
	if (size == NULL)
		return (NULL);
	temp = ft_strmerger(3, XPM_PATH, square.color, "_");
	if (temp == NULL)
	{
		free(size);
		return (NULL);
	}
	out = ft_strmerger(5, temp, size, "x", size, ".xpm");
	free(size);
	free(temp);
	return (out);
}

static char	*ft_gen_xpm_content(t_square square)
{
	char	*content;
	char	*temp;
	char	*map;

	temp = ft_itoa(square.size);
	if (temp == NULL)
		return (NULL);
	content = ft_strmerger(5, XPM_HEADER, temp, " ", temp, " 1 1\",\n\"");
	free(temp);
	if (content == NULL)
		return (NULL);
	temp = ft_strmerger(5, "/* XPM */", content, "a c ", square.color, "\",\n");
	free(content);
	if (temp == NULL)
		return (NULL);
	map = ft_square(square.size);
	if (map == NULL)
	{
		free(temp);
		return (NULL);
	}
	content = ft_strmerger(3, temp, map, "};");
	free(temp);
	free(map);
	return (content);
}

char	*ft_xpm_gen_file(t_square square)
{
	char	*file_content;
	char	*path;
	int		fd;

	path = name_generator(square);
	if (path == NULL)
		return (NULL);
	fd = open(path, O_RDONLY);
	if (fd == -1)
	{
		file_content = ft_gen_xpm_content(square);
		fd = open(path, O_WRONLY | O_CREAT, 0644);
		if (fd == -1)
		{
			free(path);
			return (NULL);
		}
		write(fd, file_content, ft_strlen(file_content));
		if (fd != -1)
			close(fd);
		free(file_content);
	}
	else
		close(fd);
	return (path);
}
