#include "philo.h"

int	diff_time(t_time old, struct timeval new)
{
	return ((new.tv_sec - old.ts) * 1000 + (new.tv_usec - old.tu) / 1000);
}

int	is_dead(t_philo *philo)
{
	struct timeval	stime;
	long int		time_stamp;
	int				time;

	if (philo->global->n_eat == philo->params->n_phi)
	{
		philo->global->dead = 1;
		return (1);
	}
	gettimeofday(&stime, NULL);
	time = diff_time(philo->t_last_meal, stime);
	if (time >= philo->params->t_die)
	{
		pthread_mutex_lock(&(philo->global->m_print));
		philo->global->dead = 1;

		time_stamp = (stime.tv_sec - philo->global->t_start.ts) * 1000;
		time_stamp += (stime.tv_usec - philo->global->t_start.tu) / 1000;
		ft_printf("%s%i %i died%s\n", B_RED, time_stamp, philo->p_nbr, RESET);
		pthread_mutex_unlock(&(philo->global->m_print));
		return (1);
	}
	return (0);
}

void	launch_threads(t_philo *philo, pthread_t *id)
{
	int	i;

	i = 0;
	while (i < philo->params->n_phi)
	{
		pthread_create(&id[i], NULL, &philo_exec, philo);
		philo = philo->next;
		i++;
	}
	while (philo->global->dead == 0)
	{
		is_dead(philo);
		philo = philo->next;
	}
	i = 0;
	while (i < philo->params->n_phi)
	{
		pthread_create(&id[i], NULL, &philo_exec, philo);
		philo = philo->next;
		i++;
	}
}
