/*****************************************************************************

        GRAOUMF TRACKER 2
        Author: Laurent de Soras, 1996-2016

--- Legal stuff ---

This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.

*****************************************************************************/



/*\\\ FICHIERS INCLUDE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/

#include	<assert.h>
#include	<stdio.h>

#include	<process.h>
#define	WIN32_LEAN_AND_MEAN
#define	NOMINMAX
#include <windows.h>
#include <windowsx.h>

#include	"base.h"
#include	"base_ct.h"
#include	"log.h"
#include	"Thread.h"
#include	"ThreadCbInterface.h"



/*\\\ CONSTANTES PUBLIQUES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/



/*\\\ CONSTANTES PRIVEES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/



/*\\\ TYPES & STRUCTURES PRIVEES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/



/*\\\ DEFINITION DES VARIABLES DE CLASSE PUBLIQUES \\\\\\\\\\\\\\\\\\\\\\\\\*/



/*\\\ DEFINITION DES VARIABLES DE CLASSE PRIVEES \\\\\\\\\\\\\\\\\\\\\\\\\\\*/



/*\\\ METHODES PUBLIQUES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/



/*==========================================================================*/
/*      Nom: (constructeur)                                                 */
/*      Description: Initialise                                             */
/*      Parametres en entree:                                               */
/*        - thread_function_ptr: pointeur sur la fonction qui accueille le  */
/*                               nouveau thread. Elle doit etre du type:    */
/*                               signed int (*thread_function_ptr) (void)   */
/*==========================================================================*/

Thread::Thread (ThreadCbInterface &callback_obj)
:	_handle (0)
,	_id (0)
,	_callback_obj (callback_obj)
,	_running_flag (false)
,	_init_flag (false)
,	_priority (Thread_PRIORITY_NORMAL)
{
	assert (&callback_obj != 0);
}



/*==========================================================================*/
/*      Nom: (destructeur)                                                  */
/*      Description: Detruit                                                */
/*==========================================================================*/

Thread::~Thread (void)
{
	while (_running_flag)
	{
		::Sleep (0);
	}
}



/*==========================================================================*/
/*      Nom: check_ok                                                       */
/*      Description: Verifie l'intergrite de l'objet.                       */
/*      Retour: 0 si l'objet parait correct.                                */
/*==========================================================================*/

signed int	Thread::check_ok (void) const
{
	if (this == NULL)
	{
		LOG_printf ("Thread::check_ok: Error: \"this\" pointer is NULL.\n");
		return (-1);
	}

	/*** A faire ***/

	return (0);
}



/*==========================================================================*/
/*      Nom: self_display                                                   */
/*      Description: Affiche "textuellement" le contenu courant de l'objet. */
/*==========================================================================*/

void	Thread::self_display (void) const
{

	/*** A faire ***/

}



signed int	Thread::spawn (void)
{
	if (_running_flag)
	{
		return (-1);
	}

	_init_flag = false;
	_priority = Thread_PRIORITY_NORMAL;
	_handle = (HANDLE) _beginthread (redirect, 0, (void *)this);
	if (_handle == NULL)
	{
		LOG_printf ("Thread::Thread: Error: couldn't create thread.\n");
		return (-1);
	}

	while (! _init_flag)
	{
		::Sleep (0);
	}
	_init_flag = false;

	return (0);
}



signed int	Thread::set_priority (Thread_Priority priority)
{
	static const int	priority_table [] =
	{
		THREAD_PRIORITY_IDLE,
		THREAD_PRIORITY_BELOW_NORMAL,
		THREAD_PRIORITY_NORMAL,
		THREAD_PRIORITY_ABOVE_NORMAL,
		THREAD_PRIORITY_TIME_CRITICAL
	};

	assert (priority >= 0);
	assert (priority < sizeof (priority_table) / sizeof (priority_table [0]));

	if (::SetThreadPriority (_handle, priority_table [priority]) == 0)
	{
		LOG_printf ("Thread::set_priority: Error: couldn't set thread priority to %d.\n",
		         priority);
		return (-1);
	}

	_priority = priority;

	return (0);
}



Thread_Priority	Thread::get_priority (void) const
{
	return (_priority);
}



bool	Thread::is_running (void) const
{
	return (_running_flag);
}



signed int	Thread::post_message (Thread_Message message)
{
	int		try_cnt;

	try_cnt = 0;
	while (! _running_flag)
	{
		::Sleep (10);
		try_cnt ++;
		if (try_cnt > 1500)	// 15 sec.
		{
			LOG_printf ("Thread::post_message: Error: Timeout. Thread isn't running /?.\n");
			return (-1);
		}
	}

	if (::PostThreadMessageW (_id, WM_USER + message, 0, 0) == 0)
	{
		LOG_printf ("Thread::post_message: Error: Couldn't send message.\n");
		return (-1);
	}

	return (0);
}



Thread_Message	Thread::get_message (void)
{
	::MSG				msg;

	if (::PeekMessageW (&msg, NULL, 0, 0, PM_NOREMOVE) == 0)
	{
		return (Thread_MESSAGE_NONE);
	}

	if (! ::GetMessageW (&msg, NULL, 0, 0))
	{
		return (Thread_MESSAGE_QUIT);
	}

	return ((Thread_Message) (msg.message - WM_USER));
}



void	Thread::sleep (long time_ms)
{
	::Sleep (time_ms);
}



void __cdecl	Thread::redirect (void *thread_ptr)
{
	assert (thread_ptr != 0);

	::MSG				msg;
	::PeekMessageW (&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);	// Force le thread a avoir une queue de messages

	Thread *		real_thread_ptr = reinterpret_cast <Thread *> (thread_ptr);
	assert (&real_thread_ptr->_callback_obj != 0);
	assert (! real_thread_ptr->_init_flag);
	assert (! real_thread_ptr->_running_flag);

	real_thread_ptr->_id = ::GetCurrentThreadId ();
	real_thread_ptr->_running_flag = true;
	real_thread_ptr->_init_flag = true;
	real_thread_ptr->_callback_obj.run_thread ();
	real_thread_ptr->_running_flag = false;
}



/*\\\ METHODES PRIVEES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/



/****************************************************************************/
/*                                                                          */
/*                                                                          */
/*                                                                          */
/****************************************************************************/



/*==========================================================================*/
/*      Nom:                                                                */
/*      Description:                                                        */
/*      Parametres en entree:                                               */
/*      Parametres en sortie:                                               */
/*      Parametres en entree/sortie:                                        */
/*      Retour:                                                             */
/*==========================================================================*/
