/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   s_lvars.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: rbousset <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/14 17:19:27 by rbousset          #+#    #+#             */
/*   Updated: 2020/02/14 17:19:29 by rbousset         ###   ########lyon.fr   */
/*                                                                            */
/* ************************************************************************** */

#include <libft.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#include "s_struct.h"

void	lvars_rebind(t_lvars **lvars, const char name[], const char newval[])
{
	t_lvars	*tmp;

	tmp = *lvars;
	while (tmp != NULL && ft_strncmp(tmp->name, name, ft_strlen(name) + 1) != 0)
	{
		tmp = tmp->next;
	}
	if (tmp == NULL)
	{
		return ;
	}
	ft_memdel((void*)&tmp->val);
	if ((tmp->val = ft_strdup(newval)) == NULL)
	{
		ft_dprintf(STDERR_FILENO, "%s\n", strerror(errno));
	}
}

void	lvars_delone(t_lvars **lvars, const char name[])
{
	t_lvars	*tmp;
	t_lvars	*prev;

	tmp = *lvars;
	if (tmp != NULL && !ft_strncmp(tmp->name, name, ft_strlen(name) + 1))
	{
		*lvars = tmp->next;
		ft_memdel((void*)&tmp->name);
		ft_memdel((void*)&tmp->val);
		ft_memdel((void*)&tmp);
		return ;
	}
	while (tmp && ft_strncmp(tmp->name, name, ft_strlen(name) + 1))
	{
		prev = tmp;
		tmp = tmp->next;
	}
	if (tmp == NULL)
		return ;
	prev->next = tmp->next;
	ft_memdel((void*)&tmp->name);
	ft_memdel((void*)&tmp->val);
	ft_memdel((void*)&tmp);
}

void	lvars_add_front(t_lvars **alvars, t_lvars *new)
{
	if (alvars == NULL || new == NULL)
	{
		return ;
	}
	new->next = *alvars;
	*alvars = new;
}

void	lvars_clear(t_lvars **lvars)
{
	t_lvars	*tmp;
	t_lvars	*renext;

	if (lvars == NULL)
		return ;
	tmp = *lvars;
	while (tmp != NULL)
	{
		renext = tmp->next;
		ft_memdel((void*)&tmp->name);
		ft_memdel((void*)&tmp->val);
		ft_memdel((void*)&tmp);
		tmp = renext;
	}
	*lvars = NULL;
}

t_lvars	*lvars_new(const char name[], const char val[])
{
	t_lvars	*link;

	if ((link = (t_lvars*)malloc(sizeof(t_lvars))) == NULL)
	{
		return (NULL);
	}
	if ((link->name = ft_strdup(name)) == NULL)
	{
		return (NULL);
	}
	if ((link->val = ft_strdup(val)) == NULL)
	{
		return (NULL);
	}
	link->next = NULL;
	return (link);
}