/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   m_prompt.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 <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <limits.h>

#include "d_define.h"
#include "m_prompt.h"
#include "m_prompt_seq.h"
#include "s_struct.h"
#include "u_vars.h"

static void	m_subst_prompt_rice(char var[], t_msh *msh)
{
	size_t	i;

	i = 0;
	while (var[i] != C_NUL)
	{
		if (var[i] == C_BACKS)
		{
			m_prompt_sequences(var, i);
			m_prompt_sequences_next(var, i, msh);
			m_prompt_sequences_more(var, i, msh);
			i = m_prompt_sequences_again(var, i, msh);
		}
		i++;
	}
}

static void	m_update_psx(uint8_t x, t_msh *msh)
{
	char	var[ARG_MAX];
	char	psx[5];

	ft_sprintf(psx, "$PS%hhu", x);
	u_get_var_value(var, psx, ARG_MAX, msh);
	if (var[0] == C_NUL)
	{
		msh->ps[x - 1][0] = '\0';
		return ;
	}
	m_subst_prompt_rice(var, msh);
	ft_strlcpy(msh->ps[x - 1], var, 255);
}

void		m_prompt_psx(uint8_t x, t_msh *msh)
{
	m_update_psx(x, msh);
	ft_dprintf(STDERR_FILENO, "%s", msh->ps[x - 1]);
}