#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#pragma comment(lib, "user32.lib")
#include "WIAClientSMCPP.h"

extern "C" {

/*
// Structure de données à associer à la mémoire partagée
*/
#include "WIAClientSM_info.h"
#include <SMCore.h>

static WIAClientLibObjects *shared_data;
static WIAClientLibObjects old_shared_data;
static int wiaclient_sm_index=-1;
static bool first_time_access;
static bool is_shared_memory_already_initialized=false;

  //----------------------------------------

  int create_wiaclient_sm()
  {
	  wiaclient_sm_index = create_shared_memory(WIACLIENT_SM_NAME, sizeof(WIAClientLibObjects) );
	  return wiaclient_sm_index;
  }

  //----------------------------------------

  int attach_wiaclient_sm()
  {
	  wiaclient_sm_index = init_shared_memory(WIACLIENT_SM_NAME, (void **)&shared_data);
	  return wiaclient_sm_index;
  }

  //----------------------------------------

  int copy_wiaclient_data_to_sm(WIAClientLibObjects *wiaclient_data)
  {
	  if (wiaclient_sm_index == -1)
		  return -1;
	  copy_data_to_shared_memory(wiaclient_sm_index, (const void *)wiaclient_data, sizeof(WIAClientLibObjects) );
	  return wiaclient_sm_index;
  }


  //----------------------------------------

   bool is_wiaclient_connected()
   {
	   return shared_data->is_wiaclient_connected;
   }

  //----------------------------------------

   void reset_wiaclient_connected()
   {
	   shared_data->is_wiaclient_connected = false;
   }

  //----------------------------------------
   int get_jpeg_length()
   {
	   return shared_data->data.jpeg_stream_len;
   }

  //----------------------------------------
   BYTE * get_jpeg_data()
   {
	   return shared_data->data.jpeg_stream_data;
   }


     //----------------------------------------
   void copy_jpeg_data(void *cpy_data)
   {
	   ((wiaclient_data *)cpy_data)->jpeg_stream_len = shared_data->data.jpeg_stream_len;
	   memcpy( ((wiaclient_data *)cpy_data)->jpeg_stream_data, shared_data->data.jpeg_stream_data, sizeof(wiaclient_data));
   }

  //----------------------------------------
   
   long get_wiaclient_frame_id()
   {
	   if ( !is_wiaclient_connected()) 
 	      return NO_VALID_FRAME;

	   return shared_data->id;
   }

   //----------------------------------------

   int get_wiaclient_frame_sec( double *sec)
   {
	   if ( !is_wiaclient_connected())
	   {
		   *sec = NULL;
 	      return NO_VALID_FRAME;
	   }

	   *sec = shared_data->sec;
	
	   return VALID_FRAME_OK;
   }

   //----------------------------------------

}