/* KInterbasDB Python Package - Implementation of Platform Infrastructure for
 *                                                Windows
 *
 * Version 3.3
 *
 * The following contributors hold Copyright (C) over their respective
 * portions of code (see license.txt for details):
 *
 * [Original Author (maintained through version 2.0-0.3.1):]
 *   1998-2001 [alex]  Alexander Kuznetsov   <alexan@users.sourceforge.net>
 * [Maintainers (after version 2.0-0.3.1):]
 *   2001-2002 [maz]   Marek Isalski         <kinterbasdb@maz.nu>
 *   2002-2007 [dsr]   David Rushby          <woodsplitter@rocketmail.com>
 * [Contributors:]
 *   2001      [eac]   Evgeny A. Cherkashin  <eugeneai@icc.ru>
 *   2001-2002 [janez] Janez Jere            <janez.jere@void.si>            */

/* This source file is designed to be directly included in _kievents.c,
 * without the involvement of a header file. */

/* NOTE: THE CODE IN THIS FILE IS TYPICALLY EXECUTED WHEN THE GIL IS NOT HELD,
 * SO IT MUST NOT CALL THE PYTHON C API! */

#ifdef ENABLE_CONNECTION_TIMEOUT
static PlatformThreadRefType Thread_current_ref() {
  return GetCurrentThread();
} /* Thread_current_ref */
#endif /* ENABLE_CONNECTION_TIMEOUT */

static PlatformThreadIdType Thread_current_id() {
  return GetCurrentThreadId();
} /* Thread_current_id */

static boolean Thread_ids_equal(
    PlatformThreadIdType a, PlatformThreadIdType b
  )
{
  return (boolean) (a == b);
} /* Thread_ids_equal */

static PlatformThreadRefType Thread_create(
    PlatformThreadFuncType func, void *func_arg,
    PlatformThreadIdType *store_thread_id
  )
{
  HANDLE t = CreateThread(
      NULL, /* default security attributes */
      0, /* default stack size */
      func, /* thread should run this func */
      func_arg, /* passing this arg */
      0, /* default creation flags (start immediately) */
      store_thread_id
    );
  return t ? t : THREAD_REF_INVALID;
} /* Thread_create */

static long Thread_join(PlatformThreadRefType t) {
  return WaitForSingleObject(t, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
} /* Thread_join */

#ifdef ENABLE_CONNECTION_TIMEOUT
static void sleep_millis(unsigned int millis) {
  Sleep(millis);
} /* sleep_millis */
#endif /* ENABLE_CONNECTION_TIMEOUT */

static long Mutex_init(PlatformMutexType *cs) {
  InitializeCriticalSection(cs);
  return 0;
} /* Mutex_init */

static long Mutex_close(PlatformMutexType *cs) {
  DeleteCriticalSection(cs);
  return 0;
} /* Mutex_destroy */

static long Mutex_lock(PlatformMutexType *cs) {
  EnterCriticalSection(cs);
  return 0;
} /* Mutex_lock */

static long Mutex_unlock(PlatformMutexType *cs) {
  LeaveCriticalSection(cs);
  return 0;
} /* Mutex_unlock */
