/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   generic.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: hulamy <hulamy@student.42.fr>              +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/01/26 15:30:54 by hulamy            #+#    #+#             */
/*   Updated: 2022/01/30 15:47:44 by hulamy           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "philo.h"

void	init_time(t_philo *philo)
{
	struct timeval	stime;

	pthread_mutex_lock(&(philo->global->m_init_time));
	if (philo->global->t_start.ts == 0)
	{
		gettimeofday(&stime, NULL);
		philo->global->t_start.ts = stime.tv_sec;
		philo->global->t_start.tu = stime.tv_usec;
	}
	pthread_mutex_lock(&(philo->m_time));
	philo->t_last_meal.ts = philo->global->t_start.ts;
	philo->t_last_meal.tu = philo->global->t_start.tu;
	pthread_mutex_unlock(&(philo->m_time));
	pthread_mutex_unlock(&(philo->global->m_init_time));
}

void	update_time(t_philo *philo)
{
	struct timeval	stime;

	pthread_mutex_lock(&(philo->m_time));
	gettimeofday(&stime, NULL);
	philo->t_last_meal.ts = stime.tv_sec;
	philo->t_last_meal.tu = stime.tv_usec;
	pthread_mutex_unlock(&(philo->m_time));
}

int	diff_time(t_philo *philo, struct timeval *new)
{
	int		t_diff;
	t_time	old;

	pthread_mutex_lock(&philo->m_time);
	old = philo->t_last_meal;
	t_diff = (new->tv_sec - old.ts) * 1000 + (new->tv_usec - old.tu) / 1000;
	pthread_mutex_unlock(&philo->m_time);
	return (t_diff);
}

int	print_message(t_philo *philo, char *clr, char *msg)
{
	long int		time_stamp;
	struct timeval	stime;

	pthread_mutex_lock(&(philo->global->m_print));
	pthread_mutex_lock(&(philo->global->m_stop));
	if (philo->global->stop)
	{
		pthread_mutex_unlock(&(philo->global->m_stop));
		pthread_mutex_unlock(&(philo->global->m_print));
		return (1);
	}
	pthread_mutex_unlock(&(philo->global->m_stop));
	gettimeofday(&stime, NULL);
	time_stamp = (stime.tv_sec - philo->global->t_start.ts) * 1000;
	time_stamp += (stime.tv_usec - philo->global->t_start.tu) / 1000;
	printf("%s%li %i %s%s\n", clr, time_stamp, philo->p_nbr, msg, RESET);
	pthread_mutex_unlock(&(philo->global->m_print));
	return (0);
}
